JavaSE-11.1.4【多态案例-猫和狗】
package day2.yubaby01.p4; /* 1.5 多态案例-猫和狗 */ public class AnimalDemo { public static void main(String[] args) { Animal a = new Cat(); a.setName("tom"); a.setAge(3); System.out.println(a.getName() + "," + a.getAge()); a.eat(); a = new Cat("tom", 3); System.out.println(a.getName() + "," + a.getAge()); a.eat(); Animal aa = new Dog(); aa.setName("sam"); aa.setAge(1); System.out.println(aa.getName() + "," + aa.getAge()); aa.eat(); aa = new Dog("sam", 1); System.out.println(aa.getName() + "," + aa.getAge()); aa.eat(); } }
package day2.yubaby01.p4; public class Animal { private String name; private int age; public Animal() { } public Animal(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void eat(){ System.out.println("动物进食"); } }
package day2.yubaby01.p4; public class Cat extends Animal{ public Cat() { } public Cat(String name, int age) { super(name, age); } @Override public void eat(){ System.out.println("猫吃啥?"); } }
package day2.yubaby01.p4; public class Dog extends Animal{ public Dog() { } public Dog(String name, int age) { super(name, age); } @Override public void eat(){ System.out.println("狗吃啥?"); } }