首页 > 编程语言 > 详细

Java:instanceof

时间:2021-04-20 20:58:04      阅读:14      评论:0      收藏:0      [点我收藏+]

instanceof:判断一个对象跟某一个类有什么联系


package com.jiemyx.oop.demo09;

public class Person {
    
}

package com.jiemyx.oop.demo09;

public class Student extends Person{
    
}

package com.jiemyx.oop.demo09;

public class Teacher extends Person{
    
}


package com.jiemyx.oop.demo09;

public class Application {
    public static void main(String[] args) {
        //Object > String
        //Object > Person > Student
        //Object > Person > Teacher
		
        //System.out.println(x instanceof Y);
        //对象x的引用类型 比如Student 与Y类存在继承关系,编译通过,
        //然后判断实际类型 比如new Student() 是否跟Y类存在关系,存在关系true,不存在关系false

        Student s = new Student();
        System.out.println(s instanceof Object);    //true
        System.out.println(s instanceof Person);    //true
        System.out.println(s instanceof Student);   //true
        //System.out.println(s instanceof Teacher);   //编译报错
        //System.out.println(s instanceof String);    //编译报错

        System.out.println("===============");

        Person p = new Student();
        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 Teacher);   //false
        //System.out.println(p instanceof String);    //编译报错

        System.out.println("===============");

        Object o = new Student();
        System.out.println(o instanceof Object);    //true
        System.out.println(o instanceof Person);    //true
        System.out.println(o instanceof Student);   //true
        System.out.println(o instanceof Teacher);   //false
        System.out.println(o instanceof String);    //false
    }
}

运行结果:

true
true
true

===============
true
true
true
false

===============
true
true
true
false
false

Java:instanceof

原文:https://www.cnblogs.com/Jiemyx/p/14682616.html

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