instanceof是Java的一个二元操作符,和==,>,<是同一类东东。由于它是由字母组成的,所以也是Java的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean类型的数据。
package oop.Demo08;
public class Main {
public static void main(String[] args) {
//object>person>teacher
//object>person>student
//object>String
Object object = new Student();
// System.out.println(x instanceof y);能不能编译通过
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Teacher);//fause
System.out.println(object instanceof String);//fause
System.out.println("==========================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Teacher);//fause
// 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 Object);//true
System.out.println(student instanceof Person);//true
// System.out.println(student instanceof Teacher);
// System.out.println(student instanceof String);//编译报错
}
}
1、能否编译通过,看类,x与y的类(x与y本身就是类),若存在父子或者子父关系可编译
2、若x与y不存在子父关系,如teacher与student,就不可编译
3、编译过后T/F看引用指向对象,x指向的对象如果是后面y的子类,则为T
package oop.Demo08;
public class Main {
public static void main(String[] args) {
//类型之间的转换:基本类型转换 高->低
Person ak = new Student();
// student.go;//报错
//student将这个对象转换为Student类型,我们就可以使用Student类型的方法了
Student ak1 = (Student) ak;
ak1.go();
}
}
//父类的引用指向子类的对象
//把父类转换为子类,向下转型;
//把子类转换为父类:强制转换,可能会丢失方法
//方便方法的调用,减少重复的代码!简洁