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

Day23-多态,instanceof和类型转换

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

Day23-多态,instanceof和类型转换

多态

即同一方法可以根据发送对象的不同而采用多种不同的行为方式。
一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多。

多态存在的条件:
有继承关系
子类重写父类方法
父类引用指向子类对象

注意:多态是方法的多态,属性没有多态性。

instanceof 和类型转换
package OOP.Demo05;

public class Application {
    public static void main(String[] args) {
        //0bject > String
        //object > Person > Teacher
        //0bject > Person > Student
        // System.out.println(X instanceof Y);能不能编译通过就看X与Y有没有父子关系,true和false看X指向的实际类型是不是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); //编译报错,没有父子关系

        //类型之间的转换  父   子
        Person obj = new Student();
        //obj.go();报错!将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
//        Student student = (Student)obj;
//        student.go();
        ((Student)obj).go();//可以总结成这句
        
    }
}
package OOP.Demo05;

public class Person {
}
package OOP.Demo05;

public class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}
package OOP.Demo05;

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

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

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