多态理解

多态就是接口在不同实例的不同表现形式

就像打印机一样有黑白的打印机,也有彩色的打印机

 

下面附一张照片


public class DT {
public static void main(String[] args) {
show(new Cat());
show(new dog());

Animal animal = new Cat(); //向上转型
animal.eat();
Cat c = (Cat)animal;//向下转型
c.work();
}
public static void show(Animal animal) {
animal.eat();
//类型判断
if (animal instanceof Cat) {
Cat c = (Cat)animal;
c.work();
}else if (animal instanceof dog) {
dog d = (dog)animal;
d.work();
}{

}
}
}
abstract class Animal{
abstract void eat();
}

class Cat extends Animal{
public void eat() {
System.out.println("吃鱼");
}
public void work() {
System.out.println("抓老鼠");
}
}
class dog extends Animal{
public void eat() {
System.out.println("吃骨头");
}
public void work() {
System.out.println("看家");
}
}

posted on 2019-03-25 21:44  JETIME庚  阅读(130)  评论(0编辑  收藏  举报

导航