今天,利用抽象类、多态性来构建一个简单的创建动物的系统。
1.创建Animal抽象类
定义成员属性名字、年龄,定义吃的抽象方法
public abstract class Animal {
private String name;
private int age;
public Animal(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 abstract void eat();
}
2.创建Cat类
继承Animal,重写吃这个方法
public class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("The cat likes eating fish.");
}
}
3.创建Dog类
继承Animal类,重写吃这个方法
public class Dog extends Animal {
public Dog(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("The dog likes eating bones.");
}
}
4.创建Demo测试类
在Demo中,new一个animal1和animal2,分别叫做“元宝”、”福福“,年龄都为一岁
public class Demo {
public static void main(String[] args) {
Animal animal1 = new Cat("yuanBao", 1);
Animal animal2 = new Dog("fuFu", 1);
System.out.println(animal1.getName());
System.out.println(animal1.getAge());
System.out.println(animal2.getName());
System.out.println(animal2.getAge());
}
}
运行结果: