instanceof的作用:判断两个类是否存在父子关系
instanceof
是一个用于确定对象是否由特定类或其子类创建的运算符。如果对象是由该类或其子类创建的,则 instanceof
返回 true
,否则返回 false
。
instanceof代码示例:
//父类 public class Person { }
//子类01 public class Student extends Person { }
//子类02 public class Teacher extends Person { }
//使用 public class Application { public static void main(String[] args) { //父>子 //object > String //object > Person > Teacher //object > Person > Student Object object = new Student(); System.out.println(object instanceof Student);//true //object instanceof Student===object和Student是否满足父子类型 System.out.println(object instanceof Person); //true System.out.printin(object instanceof object); //true System.out.println(object instanceof Teacher);//False System.out.println(object instanceof Istring); //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 0bject); //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 0bject); //true //System.out.println(student instanceof Teacher);//编译报错 //System.out.printLn(student instanceof String);//编译报错! } }
类型转换
(基本类型转换)数据转换:高转低==》强转 || 低转高==》不用强转
类型转换:父(高)===》 子(低)强转 || 子(低)===》父(高)不用强转
//父类 public class Person { public void run(){ System.out.println("run"); } }
//子类01 public class Student extends Person { public void go(){ System.out.println("go"); } }
//使用 public class Application { public static void main(String[] args) { //高(Person)===============低(Student) Person fu = new Student(); //由于go是Student类的方法,所以父类fu无法调用go方法 //所以将fu强转成student类型再调用go方法 ((student)fu).go(); Student zi = new Student(); //go方法是子类型Student的方法,所以zi可以直接使用go方法 zi.go(); //zi转换成Person类型可以直接转换 Person person = zi; //但是zi转换后会丢失Student类型的方法所以不能再直接使用go方法 ((Student)person).go(); //zi类型转换成person后可以直接使用run方法,但无法直接使用go方法 person.run(); } }
一部分总结:
-
多态存在条件:父类引用指向子类的对象
-
父类转子类,需要强转,例如:Student zi = (Student)fu
-
子类转父类,不需要强转,例如:Person person = zi;
-
为什么要转换:方便方法调用,减少重复代码