/*
多态练习:猫狗案例
*/
class Animal{
public void eat(){
System.out.println("吃饭");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("狗吃肉");
}
public void lookDoor(){
System.out.println("狗看门");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("猫吃鱼");
}
public void playGame(){
System.out.println("猫捉迷藏");
}
}
class DouTaiTest{
public static void main(String[] args){
//定义为狗
Animal a = new Dog();
a.eat();
System.out.println("----------------------");
//还原成狗
Dog d = (Dog)a;
d.eat();
d.lookDoor();
System.out.println("----------------------");
//变成猫
a = new Cat();
a.eat();
System.out.println("----------------------");
//还原成猫
Cat c = (Cat)a;
c.eat();
c.playGame();
//错误的内容
//编译错误
//Dog dd = new Animal();
//Dog ddd = new Cat();
//ClassCastException:类型转换异常(运行错误)
Dog dd = (Dog)a;
}
}
面向对象_多态版猫狗案例
最新推荐文章于 2022-03-25 22:13:10 发布