首页 > 其他 > 详细

instanceof

时间:2021-01-22 16:48:42      阅读:23      评论:0      收藏:0      [点我收藏+]

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();
        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(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类;
  • 一个对象属于一个类或者接口,必然属于该类的父类或者父接口;
  • 任意一个对象都可以判断是否属于任何一个接口;
  • 一个对象不能用于判断是否属于和该对象所属的类没有任何关系的类,会报错。

instanceof

原文:https://www.cnblogs.com/denghui-study/p/14313092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!