java 多态知识点2

public class demo0629 {
    public static void main(String[] args){
        Persons p = new Student();//向上转型
        p.eat();
        Student s = (Student) p;//向下转型
        s.eat();
        s.play();
    }
}
/*
    多态的弊端
        父类引用不能使用子类中特有的内容

        怎么解决?
            向下转型来解决这个问题
            向上转型
                FU fu = new Zi()
            向下转型
                 Student s = (Student) p;
            注意:向下专项转不好容易出现异常,ClassCastException类型转化错误
                类似:
 */
class Persons{
    public void eat(){
        System.out.println("吃饭");
    }
}
class Student extends Persons{
    public void eat(){
        System.out.println("吃肉");
    }
    public void play(){
        System.out.println("玩游戏");
    }
}
class Teacher extends Persons{
    public void eat(){
        System.out.println("吃菜");
    }
    public void teach(){
        System.out.println("教游戏");
    }
}
posted @ 2024-06-29 09:35  公子Learningcarer  阅读(1)  评论(0编辑  收藏  举报