题目:
代码:?
public class testdemo1 {
public static void main(String[] args) {
person li = new person("老李", 45);
person liu = new person("老刘", 50);
dog Dog = new dog(2, "black");
cat Cat = new cat(3, "yellow");
li.keepPet(Dog,"骨头");
liu.keepPet(Cat ,"鱼");
}
}
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 void eat(String something) {
System.out.println( something);
}
}
public class dog extends animal{
public dog() {
}
public dog(int age, String color) {
super(age, color);
}
@Override
public void eat(String something){
System.out.println("dog eat"+something);
}
public void catchMouse(){
System.out.println("看家");
}
}
public class cat extends animal {
public cat() {
}
public cat(int age, String color) {
super(age, color);
}
@Override
public void eat(String something){
System.out.println("cat eat"+something);
}
public void lookHome(){
System.out.println("逮老鼠");
}
}
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(age+"岁的老王养了一只"+Dog.getColor()+","+ Dog.getAge()+"岁的宠物"
// +",狗吃"+something);
// }
// public void keepPet(cat Cat,String something){
// System.out.println(age+"岁的老李养了一只"+Cat.getColor()+ ","+Cat.getAge()+"岁的宠物"
//
// +",猫吃"+something);
// }
//利用多态对keepPet方法进行改写
public void keepPet(animal a,String something){
if(a instanceof cat){
System.out.println(age+"岁的老王养了一只"+a.getColor()+","+ a.getAge()+"岁的宠物"
+",猫吃"+something);
}else if(a instanceof dog) {
System.out.println(age+"岁的老王养了一只"+a.getColor()+","+ a.getAge()+"岁的宠物"
+",狗吃"+something);
}
else {
System.out.println("没有这种动物");
}
}
}