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

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

多态理解

 

下面附一张照片


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("看家");
}
}

相关文章:

  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2021-07-17
  • 2021-09-02
  • 2021-06-04
猜你喜欢
  • 2021-09-20
  • 2021-07-28
  • 2021-07-07
  • 2022-01-01
相关资源
相似解决方案