package day2.yubaby02.p3; /* 2.4 抽象类案例-猫和狗 */ public class AnimalDemo { public static void main(String[] args) { Animal a1 = new Cat(); a1.setName("tom"); a1.setAge(1); System.out.println(a1.getName() + "," + a1.getAge()); a1.eat(); Animal a2 = new Cat("tom", 1); System.out.println(a2.getName() + "," + a2.getAge()); a2.eat(); Animal a3 = new Dog(); a3.setName("sam"); a3.setAge(2); System.out.println(a3.getName() + "," + a3.getAge()); a3.eat(); Animal a4 = new Dog("sam", 2); System.out.println(a4.getName() + "," + a4.getAge()); a4.eat(); } }
package day2.yubaby02.p3; public abstract 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("动物进食"); }*/ public abstract void eat(); }
package day2.yubaby02.p3; public class Cat extends Animal{ public Cat() { } public Cat(String name, int age) { super(name, age); } //技巧-子类重载父抽象类中的抽象方法,键入eat,idea候选选中自动生成函数 @Override public void eat() { System.out.println("猫吃啥?"); } }
package day2.yubaby02.p3; public class Dog extends Animal{ public Dog() { } public Dog(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("狗吃啥?"); } }