instanceof(类型判断)
测试对象 instanceof 测试类
instanceof(类型判断):判断一个对象是什么类型(引用类型),或者判断两个类是否存在父子关系。返回的结果为Boolean类型,true/false。
具体作用:测试左边的对象是否是右边类或者该类的子类创建的实例对象。
注意点: 使用instanceof
时,右边的测试类需要与创建的测试对象的右边的声明类型和左边的类
的其中任意一个有继承关系,或者在一条继承线上才能进行类型比较,否则会直接编译报错。
父类:Person
public class Person {
public void run(){
System.out.println("run");
}
}
子类:Student
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
子类:Teacher
public class Teacher extends Person{
}
main
方法
public static void main(String[] args) {
//instanceof
//继承线:
//Object -> String
//Object -> Person -> Teacher
//Object -> Person -> Student
Object object = new Student();
//instanceof,object的引用类型为Object,继承线为:Object -> Person -> Student
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof String);//false
System.out.println("========================");
Person person = new Student();
//instanceof,object的引用类型为Person
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Teacher);//false
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
//System.out.println(person instanceof String);//编译报错,Person和String没有继承关系
System.out.println("========================");
Student student = new Student();
//instanceof,object的引用类型为Student
System.out.println(student instanceof Student);//true
//System.out.println(student instanceof Teacher);//编译报错
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof String);//编译报错
}
类型转换
引用类型的等级:(高)父类 > 子类(低)
- 直接转换(向上转换):把子类转成父类;做向上转换的目的:为了使用多态,提高程序的可扩展性、可维护性。
- 强制转换(向下转换):把父类转成子类;做向下转型的目的:在一种特定的时候,需要调用子类特有的方法。
main
方法
public static void main(String[] args) {
//父(高) 子(低)
Person student = new Student();//student的引用类型为Person
//两种强制转换的写法
//强制将Person引用类型的student转换成Student引用类型,调用Student类型的go()
//低-->高:(低)高
((Student) student).go();//go
Student obj = (Student) student;
obj.go();//go
//子类转换为父类,会丢失子类独有的方法
Student student1 = new Student();
student1.go();//go
//低-->高
Person person = student1;
//person.go();//编译报错,无go()方法
}