-
练习
-
实操
动物类
public class Animal { //动物 //颜色 private String color; //年龄 private int age; private String something; public Animal() { } public Animal(String color, int age,String something) { this.color = color; this.age = age; this.something = something; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSomething() { return something; } public void setSomething(String something) { this.something = something; } //行为 public void eat(String something){ } }
猫类
public class cat extends Animal{ //猫 public cat() { } public cat(String color, int age, String something) { super(color, age, something); } public void catchMouse(){ System.out.println("猫在抓老鼠"); } @Override public void eat(String something) { System.out.println(getColor()+"的"+getAge()+"岁的猫在眯着眼睛侧着吃"+getSomething()); } }
狗类
public class dog extends Animal{ //狗 public dog() { } public dog(String color, int age, String something) { super(color, age, something); } public void lookHome(){ System.out.println("狗在看家"); } @Override public void eat(String something) { System.out.println(getAge()+"岁的"+getColor()+"的狗"+"在抱着"+getSomething()+"猛吃"); } public void keepPet(person p) { } }
饲养员类
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(Animal a,String something){ if (a instanceof dog){ System.out.println(age+"岁的"+name+"养了一只"+a.getColor()+"的"+a.getAge()+"的狗"); a.eat(something); ((dog) a).lookHome(); }else if (a instanceof cat){ System.out.println(age+"岁的"+name+"养了一只"+a.getColor()+"的"+a.getAge()+"的猫"); a.eat(something); ((cat) a).catchMouse(); } } }
测试
public class test { public static void main(String[] args) { Animal a = new Animal(); dog d = new dog("五颜六色",888,"泛着金光的骨头"); d.lookHome(); d.eat("泛着金光的骨头"); cat c = new cat("黑白相间",999,"泛着彩光的鱼"); c.catchMouse(); c.eat("泛着彩光的鱼"); person p = new person("蔡徐坤",188); p.keepPet(d,"泛着金光的骨头"); p.keepPet(c,"泛着彩光的鱼"); } }
-