instanceof 的作用就是判断一个对象是什么类型。
直接看代码:
Application(主类):
public class Application {
public static void main(String[] args) {
// Object>Person>Student
// Object>Person>Teacher
// Person>String
Object student = new Student();
System.out.println(student instanceof Object);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Teacher);//false
System.out.println(student instanceof String);//false
System.out.println("===================================");
Person person = new Student();
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Teacher);//false
System.out.println("====================================");
Student student1 = new Student();
System.out.println(student1 instanceof Object);//true
System.out.println(student1 instanceof Person);//true
System.out.println(student1 instanceof Student);//true
//System.out.println(X instanceof Y)能不能编译通过?就取决于X与Y之间是否是继承关系。即子类和父类的关系
}
}
Person类(父类)、Student(子类)、Teacher(子类);
它们之间的继承关系:
Object>Person>Student
Object>Person>Teacher
运行结果:
如果子类和父类没有继承关系,则无法比较:
比如说Student和Teacher:
在Java的多态关系中,父类是无法调用子类独有的方法的,这个时候就需要进行类型转换:
直接看代码:
Application(主类):
package com.oop.demo08;
public class Application {
public static void main(String[] args) {
// 类型之间的转换 要有继承的关系才可以进行转换
// 高-------->低 强制类型转换
Person person = new Student();
// Student person1 = (Student) person;
// person1.run();
((Student)person).run();
Student student = new Student();
student.run();
Object object = student;
}
}
把子类转换为父类:向上转型,直接转(低--------->高)
把父类转换为则子类:向上转型,强制转换(高--------->低)
和之前的数据类型转换差不多。
注意:子类向上转型时,有时会丢失方法。