Java instanceof用法,判断继承.

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编译器报错.

    }

}
发布了56 篇原创文章 · 获赞 2 · 访问量 486

猜你喜欢

转载自blog.csdn.net/jarvan5/article/details/105550511