同学们看看能给优化下吗?名字不能直接一样吗?
class Demo {
public static void main(String[] args) {
Animal a = new Cat("加菲",8);
Animal b = new Dog("八公",4);
change(a);
change(b);
}
public static void change(Animal a){
a.eat();
if (a instanceof Cat) {
Cat c = (Cat)a;
c.catchMouse();
}else if (a instanceof Dog) {
Dog d = (Dog)a;
d.lookHome();
}
}
}
class Animal {
private String name;
private int age;
public Animal(){}
public Animal(String name,int age){
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName (){
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge (){
return age;
}
public void eat(){
System.out.println("吃东西");
}
}
class Cat extends Animal {
public Cat(){}
public Cat(String name,int age){
super(name,age);
}
public void eat(){
System.out.println(getName()+"吃鱼");
}
public void catchMouse(){
System.out.println(getName()+"抓老鼠"+getAge()+"年.");
}
}
class Dog extends Animal {
public Dog(){}
public Dog(String name,int age){
super(name,age);
}
public void eat(){
System.out.println(getName()+"吃肉");
}
public void lookHome(){
System.out.println(getName()+"看门"+getAge()+"年.");
}
} |
|