JAVA语言之instanceof关键字

介绍

Java 中的instanceof 运算符是用来指出对象是否是特定类的一个实例,返回值是Boolean

用法: 
result = object instanceof class 
参数: 
Result:布尔类型。 
Object:必选项。任意对象表达式。 
Class: 必选项。任意已定义的对象类。 
说明: 

如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。

如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。 

如果不存在继承关系下,编译出错  

例子

public static void main(String[] args) {
        
        Person p = new Person("l'm person");
        Student pp = new Student("l'm student");
        Object obj = null;
        
        objectOperation();
        testInstance(p, pp, obj);
    }

    public static void testInstance(Person p,Person pp ,Object obj){
        Boolean result;
        result = p instanceof Student;
        System.out.println("person p instance of student "  + result);
        result = p instanceof Person;
        System.out.println("person p instance of Person " + result);
        result = p instanceof Object;
        System.out.println("person p instance of Object " + result);
        result = p instanceof Exam;
        System.out.println("person p instance of Interface Exam " + result);

        result = pp instanceof Person;
        System.out.println( "student pp instance of Person "+ result);

        result = obj instanceof Object;
        System.out.println("null object obj instanceof Object " + result);


        // 编译出错
        // System.out.println(p instanceof System);
    }

    public static void objectOperation(){
        String a = "hello";
        String b = "java";
        Boolean result;
        result = a+b instanceof String;
        System.out.println("字符串相加仍是字符串 "+ result);
    }

class Person{
    String name = null;
    public Person(String name) {
        this.name = name;
    }
    public void shout(){
        System.out.println(name);
    }
}

class Student extends Person implements Exam{
    public Student(String name) {
        super(name);
    }
    public void getMathGrade() {}
    public void getChineseGrade() {System.out.println("这是我的语文成绩");}
}

输出

字符串相加仍是字符串 true
person p instance of student false
person p instance of Person true
person p instance of Object true
person p instance of Interface Exam false
student pp instance of Person true
null object obj instanceof Object false




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值