test类
package ploydemo4;
public class Test {
public static void main(String[] args) {
//创建对象并调用方法
/*Person p=new Person("小明",18);
Dog dog = new Dog(2,"黑色");
p.KeepPat(dog,"骨头");
Person p1=new Person("老黑",80);
Cat cat = new Cat(2,"白色");
p1.KeepPat(cat,"老鼠");*/
Person p = new Person("老王", 34);
Dog d = new Dog(2, "黄色");
Cat c = new Cat(7, "白色");
p.KeepPat(d,"骨头");
p.KeepPat(c,"小鱼干");
}
}
Person类
package ploydemo4;
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 KeepPat(Dog dog,String something){
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+dog.getColor()+"颜色的"+dog.getAge()+"岁的狗");
dog.eat(something);
}
//饲养猫
public void KeepPat(Cat cat,String something){
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+cat.getColor()+"颜色的"+cat.getAge()+"岁的猫");
cat.eat(something);
}
*/
//想要一个方法,能接受所有动物,包括猫,包括狗
//方法的形参:可以写着这些类的父类Animal
public void KeepPat(Animal animal,String something){
if(animal instanceof Dog){
Dog a=(Dog)animal;
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+a.getColor()+"颜色的"+a.getAge()+"岁的狗");
a.eat(something);
}else if(animal instanceof Cat){
Cat c=(Cat)animal;
System.out.println("年龄为"+age+"岁的"+name+"养了一只"+c.getColor()+"颜色的"+c.getAge()+"岁的猫");
c.eat(something);
}else{
System.out.println("没有这种动物");
}
}
}