动物继承
动物类
package Animal20240709;public class Animal {int age;String color;public Animal() {}public Animal(int age, String color) {this.age = age;this.color = color;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public void eat(String eatThing) {System.out.printf("颜色为%s的%d岁动物在吃%s\n", this.color, this.age, eatThing);}
}
狗类
package Animal20240709;public class Dog extends Animal{public Dog() {}public Dog(int age, String color) {super(age, color);}@Overridepublic void eat(String eatThing) {System.out.printf("颜色为%s的%d岁狗在吃%s\n", this.color, this.age, eatThing);}
}
猫类
package Animal20240709;public class Cat extends Animal{public Cat() {}public Cat(int age, String color) {super(age, color);}@Overridepublic void eat(String eatThing) {System.out.printf("颜色为%s的%d岁猫在吃%s\n", this.color, this.age, eatThing);}
}
人类
package Animal20240709;public class Person {String name;int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void keepPet(Dog dog, String something) {System.out.printf("%d岁的主人%s在喂%d岁的%s狗吃%s\n", this.age, this.name,dog.age, dog.color, something);}public void keepPet(Cat cat,String something) {System.out.printf("%d岁的主人%s在喂%d岁的%s哈基米吃%s\n", this.age, this.name,cat.age, cat.color, something);}
}
测试
package Animal20240709;
import java.util.Scanner;
public class AnimalTest {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入主人的名字");String name = sc.next();System.out.println("请输入主人的年龄");int age = sc.nextInt();Person p = new Person(name, age);System.out.println("请输入狗的毛色");String dogColor = sc.next();System.out.println("请输入狗的年龄");int dogAge = sc.nextInt();Dog d = new Dog(dogAge, dogColor);System.out.println("请输入猫的毛色");String catColor = sc.next();System.out.println("请输入猫的年龄");int catAge = sc.nextInt();Cat c = new Cat(catAge, catColor);p.keepPet(d, "骨头");p.keepPet(c, "fish");d.eat("骨头");c.eat("fish");}
}