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 void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public abstract void eat();
}
class Dog extends Animal{
public Dog(){}
public Dog(String name,int age){
super(name,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("猫吃鱼");
}
}
//测试类
public class AbstractTest {
public static void main(String [] args){
//测试狗类
//方式一:
Dog d=new Dog();
d.setName("旺财");
d.setAge(3);
System.out.println(d.getAge()+"------"+d.getName());
d.eat();
//方式二:
Dog d2=new Dog("旺财",3);
System.out.println(d2.getAge()+"------"+d2.getName());
d2.eat();
System.out.println("------------------------------------------");
//方式三:多态版
Animal a=new Dog();
a.eat();
a.setName("旺财");
a.setAge(6);
System.out.println(a.getAge()+"------"+a.getName());
Animal a2=new Dog("旺财",6);
System.out.println(a2.getAge()+"------"+a2.getName());
a2.eat();
}
}
程序运行结果为:
3------旺财
狗吃肉
3------旺财
狗吃肉
狗吃肉
6------旺财
6------旺财
狗吃肉
来源:CSDN
作者:绝代风华.
链接:https://blog.csdn.net/qq_44818449/article/details/102647065