object instanceof Object 左边是对象的实例,右边是类,用于判断2个类之间是否存在父子关系
左边的
1.下面代码的继承树(线)为:
* Object -- String
* Object -- Person -- Teacher
* Object -- Person -- Student.
*/
2.左右一线 不报错.
左边的引用类型,要和右边的类型在一个继承线上.
(左指向对象object的引用类型 )
3.右子右父 即为true
右指代 object实例的类型,new 的类型
总代码:
Person.java
package opp.instanceof比较转化和类型转化;
public class Person {
}
Student.java
package opp.instanceof比较转化和类型转化;
public class Student extends Person {
protected void goToSchool(){
System.out.println("sumClass class can go to school.");
}
}
Teacher.java
package opp.instanceof比较转化和类型转化;
public class Teacher extends Person{
}
Demo.java
package opp.instanceof比较转化和类型转化;
public class Demo {
public static void main(String[] args) {
/**
* Object -- String
* Object -- Person -- Teacher
* Object -- Person -- Student.
*/
Object object = new Student();
System.out.println("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 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 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);//false编译器报错.
}
}