栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础----面向对象编程OOP之五

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础----面向对象编程OOP之五

13.instanceof和类型转换

instanceof

instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回值为 boolean 数据类型:true 或 false。

x instanceof y : x 是不是 y 的实例,true/false 
public class Person {}		//Person类

public class Student extends Person {}		//Student类继承Person类

public class Teacher extends Person{}		//Teacher类继承Person类

public class Application {
    public static void main(String[] args) {
        //Object > Person > Student
        //Object > Person > Teacher
        //Object > String
        //x instanceof y : 看是否是继承关系
        Object object = new Student();
        System.out.println(object instanceof Student);  //true
        System.out.println(object instanceof Person);   //true
        System.out.println(object instanceof Object);   //true
        System.out.println(object instanceof Teacher);  //false
        System.out.println(object instanceof String);   //false

        Person person = new Student();
        System.out.println(person instanceof Student);  //true
        System.out.println(person instanceof Person);   //true
        System.out.println(person instanceof Object);   //true
        System.out.println(person instanceof Teacher);  //false
        //System.out.println(person instanceof String);   //不兼容的类型,无法转换

        Student student = new Student();
        System.out.println(student instanceof Student);  //true
        System.out.println(student instanceof Person);   //true
        System.out.println(student instanceof Object);   //true
        //System.out.println(student instanceof Teacher);  //不兼容的类型,无法转换
        //System.out.println(student instanceof String);   //不兼容的类型,无法转换
    }
}

类型转换

父类引用指向子类的对象把子类转换为父类,向上转型,自动转换把父类转换为子类,向下转型,须强制转换方便方法的调用,减少重复代码!、

public class Application {
    public static void main(String[] args) {
        //类型之间的转换:由高向低,需强制转换;由低向高,自动转换

        //高(Person类 父类)      低(Student、Teacher类 子类)
        Person student1 = new Student();
        //student1.eat();   //不可直接使用子类的方法!
        student1.run();     //可以直接使用类本身的方法
        //强制类型转换:将student1的类型强制转换成其子类的类型,才可以使用子类的方法
        Student student2 = (Student) student1;
        student2.eat();
        ((Student)student1).eat();

        Teacher teacher1 = new Teacher();
        teacher1.run();
        teacher1.teach();
        //低转高,子类转成父类可能会丢失子类的本身拥有的一些方法
        Person teacher2 = teacher1;
        teacher2.run();		//可以直接使用Person类的方法
        //teacher2.teach();   此时,而Teacher子类的方法就不可以直接调用了!
    }
}

------------------------------“笔记整理自跟着《狂神说Java》”----------------------------------​

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731802.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号