instanceof

instanceof用于判断某个对象是否属于某个类或者接口,若是的话就返回true,不是的话就返回false。

例:

Person类:

package com.dh.polymorphic;

public class Person {
}

Student类:继承Person类

package com.dh.polymorphic;

public class Student extends Person {
}

PersonInterface接口:

package com.dh.polymorphic;

public interface PersonInterface {
}

Teacher类:实现PersonInterface接口

package com.dh.polymorphic;

public class Teacher implements PersonInterface {
}

开始测试:

测试类:

package com.dh.polymorphic;

public class InstanceofTest {

    public static void main(String[] args) {
        //首先排列关系,别忘记了Object是所有类的鼻祖
        //Object-->Person-->Student
        //Object-->Teacher
        //         PersonInterface-->Teacher

        Person person = new Person();
        Person p = new Student();
        Student student = new Student();
        Teacher teacher = new Teacher();

        System.out.println(person instanceof Object);   //true
        System.out.println(person instanceof Person);   //true
        System.out.println(person instanceof Student);  //false
        System.out.println(person instanceof PersonInterface);  //false
//        System.out.println(person instanceof Teacher);

        //向上转型对象的判断
        System.out.println(p instanceof Object);    //true
        System.out.println(p instanceof Person);    //true
        System.out.println(p instanceof Student);   //true
        System.out.println(p instanceof PersonInterface);   //false
//        System.out.println(p instanceof Teacher);

        System.out.println(student instanceof Object);   //true
        System.out.println(student instanceof Person);   //true
        System.out.println(student instanceof Student);   //true
        System.out.println(student instanceof  PersonInterface);  //false
//        System.out.println(student instanceof Teacher);

        System.out.println(teacher instanceof Object);   //true
        System.out.println(teacher instanceof Teacher);   //true
        System.out.println(teacher instanceof PersonInterface);   //true
//        System.out.println(teacher instanceof Person);
////        System.out.println(teacher instanceof Student);
    }
}

总结:

  • 任意一个对象都属于Object类;
  • 一个对象属于一个类或者接口,必然属于该类的父类或者父接口;
  • 任意一个对象都可以判断是否属于任何一个接口;
  • 向上转型的对象,属于其子类,也属于其直接父类和父类的父类;(参考上述p)
  • 一个对象不能用于判断是否属于和该对象所属的类没有任何关系的类,会报错。
posted @ 2021-01-22 14:23  deng-hui  阅读(835)  评论(0编辑  收藏  举报