需求
1.定义动物类
属性:
年龄,颜色
行为:
eat(String something)方法(无具体行为,不同动物吃的方式和东西不一样,something表示吃的东西)
生成空参有参构造,set和get方法
2.定义狗类继承动物类
行为:
eat(String something)方法,看家lookHome方法(无参数)
3.定义猫类继承动物类
行为:
eat(String something)方法,逮老鼠catchMouse方法(无参数)
4.定义Person类
属性:
姓名,年龄
行为:
keepPet(Dog dog,String something)方法
功能:喂养宠物狗,something表示喂养的东西
该方法调用后打印结果为:颜色为黑色的2岁的狗,在吃骨头
行为:
keepPet(Cat cat,String something)方法
功能:喂养宠物猫,something表示喂养的东西
该方法调用后打印结果为:颜色为白色的2岁的猫,在吃小鱼干
5.生成空参有参构造,set和get方法
6.测试以上方法
Animal
public class Animal {
private int age;
private 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 String eat(String something) {
return "在吃" + something;
}
}
Dog
public class Dog extends Animal{
public Dog() {
}
public Dog(int age, String color) {
super(age, color);
}
public void lookHome(){
System.out.println("看家");
}
}
Cat
public class Cat extends Animal{
public Cat() {
}
public Cat(int age, String color) {
super(age, color);
}
public void catchMouse(){
System.out.println("逮老鼠");
}
}
Person
public class Person {
private String name;
private 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.println("颜色为" + dog.getColor() + "的" + dog.getAge() + "岁" + "的狗," + dog.eat(something));
}
public void keepPet(Cat cat, String something) {
System.out.println("颜色为" + cat.getColor() + "的" + cat.getAge() + "岁" + "的猫," + cat.eat(something));
}
}
Test
public class Test {
public static void main(String[] args) {
Person p = new Person("小夭", 23);
System.out.println(p.getName() + "," + p.getAge());
Dog d = new Dog(3, "金色");
p.keepPet(d, "骨头");
d.lookHome();
Cat c = new Cat(2, "银色");
p.keepPet(c, "小鱼干");
c.catchMouse();
}
}