13.instanceof和类型转换
-
instanceof
- instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。
- instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回值为 boolean 数据类型:true 或 false。
x instanceof y : x 是不是 y 的实例,true/false
public class Person {} //Person类 public class Student extends Person {} //Student类继承Person类 public class Teacher extends Person{} //Teacher类继承Person类 public class Application { public static void main(String[] args) { //Object > Person > Student //Object > Person > Teacher //Object > String //x instanceof y : 看是否是继承关系 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 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); //不兼容的类型,无法转换 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 Application { public static void main(String[] args) { //类型之间的转换:由高向低,需强制转换;由低向高,自动转换 //高(Person类 父类) 低(Student、Teacher类 子类) Person student1 = new Student(); //student1.eat(); //不可直接使用子类的方法! student1.run(); //可以直接使用类本身的方法 //强制类型转换:将student1的类型强制转换成其子类的类型,才可以使用子类的方法 Student student2 = (Student) student1; student2.eat(); ((Student)student1).eat(); Teacher teacher1 = new Teacher(); teacher1.run(); teacher1.teach(); //低转高,子类转成父类可能会丢失子类的本身拥有的一些方法 Person teacher2 = teacher1; teacher2.run(); //可以直接使用Person类的方法 //teacher2.teach(); 此时,而Teacher子类的方法就不可以直接调用了! } }
——————————“笔记整理自跟着《狂神说Java》”———————————-
版权声明:本文为gmdjx2012原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。