instanceof
instanceof是Java语言中的一个二元运算符,它的作用是:判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例,即它左边的对象是否是它右边的类的实例,该运算符返回boolean类型的数据
试验探究
我创建3个类,关系如下:
public class Student extends Person
public class Teacher extends Person
public class Person
在主类中使用instanceof进行判断
import com01.duotai.deomo.Person;
import com01.duotai.deomo.Student;
import com01.duotai.deomo.Teacher;
public class Application {
//今天学习instanceof
// Object -> Person -> Student
// Object -> Person -> Teacher
// Object -> String
public static void main(String[] args) {
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("==================================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
// System.out.println(person instanceof String);//编译报错
System.out.println("===================================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
// System.out.println(student instanceof Teacher);//编译报错
// System.out.println(student instanceof String);//编译报错
}
}
结果:
类型之间的转化
有这样一个问题:
先看代码:
public class Oldman extends Person{
public void say(){
System.out.println("Tanqi");//叹气
}
public void say1(){
System.out.println("abc");
}
}
public class Person {
public int a = 100;
public void say(){
System.out.println("ShuoHua"+a);//说话
}
}
import com01.duotai.deomo.Oldman;
import com01.duotai.deomo.Person;
import com01.duotai.deomo.Student;
import com01.duotai.deomo.Teacher;
public class Application {
public static void main(String[] args) {
Oldman o1 = new Oldman();
Person p2 = new Oldman();
o1.say();
o1.say1();
p2.say();
p2.say1();//会报错,父类中没有say1方法
}
}
在创建一个引用父类型的子类对象时,如何使该对象能调用其引用父类没有而其子类独有的方法;
答:向下强制转换。将父类转子类既可调用
public class Application {
public static void main(String[] args) {
Oldman o1 = new Oldman();
Person p2 = new Oldman();
o1.say();
o1.say1();
p2.say();
// p2.say1();//会报错,父类中没有say1方法
System.out.println("============================");
//强制转换
Oldman p3 = (Oldman)p2;
p3.say1();
((Oldman)p2).say1();
}
}
结果:
如上所示的两种强转方案都可以成功实现
另有低转高:
//子类转父类(低转高)
Student s1 = new Student();
// ((Person)s1).say1();//发现无法再调用方法s1
或
Person s2 = s1;
s2.say();//只能调用父类方法了
总结:
-
子类转父类向上转型
(( 类名 ) 对象 ). 方法 ( );
-
父类转子类向下转型(强制转换)
-
instanceof去判断对象是谁的实例