已知有如下Animal抽象类和IAbility接口,请编写Animal子类Dog类与Cat类,并分别实现IAbility接口,另外再编写一个模拟器类Simulator调用IAbility接口方法,具体要求如下。 已有的Animal抽象类定义: abstract class Animal{ private String name; //名字 private int age; //年龄 public Animal(String name, in
时间: 2024-03-29 18:42:18 浏览: 196
抽象类和接口
t age){ this.name = name; this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } public abstract void eat(); }
已有的IAbility接口定义: interface IAbility{ void run(); void swim(); }
下面是Dog类的实现:
class Dog extends Animal implements IAbility{
public Dog(String name, int age){
super(name, age);
}
public void eat(){
System.out.println(getName() + " is eating bones!");
}
public void run(){
System.out.println(getName() + " is running!");
}
public void swim(){
System.out.println(getName() + " is swimming!");
}
}
下面是Cat类的实现:
class Cat extends Animal implements IAbility{
public Cat(String name, int age){
super(name, age);
}
public void eat(){
System.out.println(getName() + " is eating fish!");
}
public void run(){
System.out.println(getName() + " is running!");
}
public void swim(){
System.out.println(getName() + " cannot swim!");
}
}
下面是Simulator类的实现:
class Simulator{
public static void main(String[] args){
Dog dog = new Dog("Buddy", 3);
Cat cat = new Cat("Kitty", 2);
dog.eat();
dog.run();
dog.swim();
cat.eat();
cat.run();
cat.swim();
}
}
当我们运行Simulator类时,输出结果如下:
Buddy is eating bones!
Buddy is running!
Buddy is swimming!
Kitty is eating fish!
Kitty is running!
Kitty cannot swim!
阅读全文