day11-java

instanceof关键字

instanceof关键字用于判断对象是否是类或其子类所创建的对象,且instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误

package com.shifan.oop.demo07;

public class Application {
    public static void main(String[] args) {
        //Object > Person > Student
        //Object > Person > Teacher
        //Object > String
        Object object = new Student();
        //true
        System.out.println(object instanceof Student);
        //true
        System.out.println(object instanceof Person);
        //true
        System.out.println(object instanceof Object);
        //false
        System.out.println(object instanceof Teacher);
        //false
        System.out.println(object instanceof String);
        System.out.println("=================================================================");
        Person person = new Student();
        //true
        System.out.println(person instanceof Student);
        //true
        System.out.println(person instanceof Person);
        //true
        System.out.println(person instanceof Object);
        //false
        System.out.println(person instanceof Teacher);
        //编译报错:System.out.println(person instanceof String);
        System.out.println("=================================================================");
        Student student = new Student();
        //true
        System.out.println(student instanceof Student);
        //true
        System.out.println(student instanceof Person);
        //true
        System.out.println(student instanceof Object);
        //编译报错:System.out.println(student instanceof Teacher);
        //编译报错:System.out.println(student instanceof String);
        //类型转换:父——子
        // 高                 低
        Person p = new Student();
        //将student1转换为Student类型即可调用Student的方法
        Student s = (Student)p;
        s.run();
        //或者:((Student)p).run();
        //子类转换为父类后,可能会丢失一些自己本来的方法,这里person1无法再调用子类的run()方法
        //低转高,自动转换
        Person person1 = student;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值