[AppleScript] 纯文本查看 复制代码 class Animal {
public void eat(){
System.out.println("eat");
}
public void sleep(){
System.out.println("sleep");
}
}
class Dog extends Animal {
public void eat(){
System.out.println("狗吃肉");
}
public void sleep(){
System.out.println("狗站着睡觉");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("猫吃鱼");
}
public void sleep() {
System.out.println("猫趴着睡觉");
}
}
//针对动物操作的工具类
class AnimalTool {
private AnimalTool(){}
public static void useAnimal(Animal a) {
a.eat();
a.sleep();
}
}
class DuoTaiDemo {
public static void main(String[] args) {
Cat c = new Cat();
c.eat();
c.sleep();
Cat c2 = new Cat();
c2.eat();
c2.sleep();
Cat c3 = new Cat();
c3.eat();
c3.sleep();
//...
System.out.println("--------------");
AnimalTool.useAnimal(c);
AnimalTool.useAnimal(c2);
AnimalTool.useAnimal(c3);
System.out.println("--------------");
Dog d = new Dog();
Dog d2 = new Dog();
Dog d3 = new Dog();
AnimalTool.useAnimal(d);
AnimalTool.useAnimal(d2);
AnimalTool.useAnimal(d3);
System.out.println("--------------");
}
}
看视频自学ing 老师讲到多态时说了这个猫狗案例 不过关于上面针对动物的操作工具不太懂 希望大神能解惑~~
35行 定义useAnimal参数是Animal a ,从57行开始可以直接调用AnimalTool.useAnimal(c); 但是前面创建对象时Cat c = new Cat();
不应该是Animal c = new Cat();吗? 按上面定义了Cat变量 useAnimal方法可以直接调用Cat类变量??
|