instanceof和类型转换
X instanceof Y 判断X和Y是否有父子关系,如果有的话为ture,没有的话为false
Object->Person->Student
Object->Person->Teacher
Object->String
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
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 Object);//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 Object);//true
//System.out.println(student instanceof Teacher);
//System.out.println(student instanceof String);
}
类型转换
Object->Person->Student
public static void main(String[] args) {
Person s1 = new Student();
((Student) s1).go();//转换为Student类型,就可以使用Student类型独有的方法了
Student student = new Student();
Person person = student;//子类转换为父类可能会丢失一些方法,子类转换为父类不需要强制转换反之则需要
}