instanceof 和类型转换
- instanceof:用来判断子类与父类之间的关系
代码示例:
父类:Person
package cheng.oop.demo05;
public class Person {
}
子类1:Teacher
package cheng.oop.demo05;
public class Teacher extends Person {
}
子类2:Student
package cheng.oop.demo05;
public class Student extends Person{
}
关系判断:
package cheng.oop;
import cheng.oop.demo05.Person;
import cheng.oop.demo05.Student;
import cheng.oop.demo05.Teacher;
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
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(person instanceof String);// 直接报错,因为没有联系
}
}
- 类型转换:
- 父类引用指向子类对象,但子类引用不能指向父类对象
- 把子类转换成父类,向上转型,可以直接转,但可能会丢失自己的一些方法。
- 把父类转换为子类,向下转型,需要强制转换。
代码示例:
// 子类转父类,直接转,可能丢失子类自己的方法
Person p = student;
// 父类转子类,需要强转
Student stu = (Student)person;