//多态的应用
class Demo_Animal6 {
public static void main(String[] args) {
System.out.println("Hello World!");
Animal c=new Cat("加肥",3);
Animal d=new Dog("忠犬",4);
c.eat();
d.eat();
Cat a=(Cat)c;
Dog b=(Dog)d;
System.out.println(c.getName()+","+c.getAge());
System.out.println(d.getName()+","+d.getAge());
a.catchMouse();
b.lookHome();
}
}
abstract 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 abstract void eat();
}
class Cat extends Animal{
public Cat(){}
public Cat(String name,int age){
super(name,age);
}
public void eat(){
System.out.println("猫吃鱼");
}
public void catchMouse(){
System.out.println("抓老鼠");
}
}
class Dog extends Animal {
public Dog(){}
public Dog(String name,int age){
super(name,age);
}
public void eat(){
System.out.println("狗吃肉");
}
public void lookHome(){
System.out.println("看家");
}
}
|
|