instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例。
其中 student为一个对象,Class 表示一个类或者一个接口,当 student 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。
注意:编译器会检查 student 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。
Application: Person是Student和Teacher的父类
package com.cheng.oop;
?
import com.cheng.oop.pol.Person;
import com.cheng.oop.pol.Student;
import com.cheng.oop.pol.Teacher;
?
public class Application {
public static void main(String[] args) {
Teacher teacher = new Teacher();//类实例化
Person person = new Person();
Student student = new Student();
?
System.out.println(teacher instanceof Person);//true
// System.out.println(teacher instanceof Student);//编译直接出错
System.out.println(teacher instanceof Object);//true
System.out.println(teacher instanceof Teacher);//true
System.out.println("============================");
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Student);//true
// System.out.println(student instanceof Teacher);//编译直接出错
System.out.println(student instanceof Object);//true
System.out.println("================================");
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Student);//false
System.out.println(person instanceof Teacher);//false
// System.out.println(person instanceof String);//编译出错
System.out.println("============================");
}
}
Application:
package com.cheng.oop;
?
import com.cheng.oop.pol.Person;
import com.cheng.oop.pol.Student;
import com.cheng.oop.pol.Teacher;
?
public class Application {
public static void main(String[] args) {
//类型之间的转换 : 父子
//高转低需强转 低转高则不需要
?
//父类 > 子类
Person person = new Teacher();//Person类
Student student = (Student) person;//将Person类强制转换为Student 高转低 Student是Person的子类
student.read();//强制转换后就可以使用read方法
//还可以一句话完成如下:
((Teacher) person).read();//意思是将person强制转换为Teacher类后调用read方法
?
?
?
?
}
}
Teacher:
package com.cheng.oop.pol;
?
public class Teacher extends Person {
public void read(){
System.out.println("Teacher.read");
}
?
}
?
Student:
package com.cheng.oop.pol;
?
public class Student extends Person {
public void read(){
System.out.println("Student.read");
}
?
}
?
此转换可以方便方法的调用,减少重复的代码。
原文:https://www.cnblogs.com/Alirious/p/14848186.html