需要编写两个接口体现特殊能力: (1)定义一个游泳的接口Swimmable,在此接口中有抽象方法swim()。 (2)定义一个游泳的接口Flyable,在此接口中有抽象方法fly()。 需要编写三个子类兔子、青蛙和老鹰: (1) 定义一个子类Rabbit,兔子不会飞也不会游泳,继承动物类,并覆写shout()和eat()方法。 (2) 定义一个子类Frog,青蛙不会飞但会游泳,继承动物类并实现接口Flyable,并覆写shout()、eat()方法和swim()方法。 (3) 定义一个子类Eagle,老鹰会飞但不会游泳,继承动物类并实现接口Swimmable,并覆写shout()、eat()方法和fly()方法。
时间: 2023-06-19 14:05:50 浏览: 175
继承中的构造方法-Java继承_抽象类与接口的应用.
接口Swimmable的代码:
```java
public interface Swimmable {
void swim();
}
```
接口Flyable的代码:
```java
public interface Flyable {
void fly();
}
```
动物类Animal的代码:
```java
public abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void shout();
public abstract void eat();
}
```
子类Rabbit的代码:
```java
public class Rabbit extends Animal {
public Rabbit(String name) {
super(name);
}
@Override
public void shout() {
System.out.println(name + " is shouting: squeak squeak");
}
@Override
public void eat() {
System.out.println(name + " is eating: carrot");
}
}
```
子类Frog的代码:
```java
public class Frog extends Animal implements Swimmable {
public Frog(String name) {
super(name);
}
@Override
public void shout() {
System.out.println(name + " is shouting: croak croak");
}
@Override
public void eat() {
System.out.println(name + " is eating: insect");
}
@Override
public void swim() {
System.out.println(name + " is swimming");
}
}
```
子类Eagle的代码:
```java
public class Eagle extends Animal implements Flyable {
public Eagle(String name) {
super(name);
}
@Override
public void shout() {
System.out.println(name + " is shouting: screech screech");
}
@Override
public void eat() {
System.out.println(name + " is eating: mouse");
}
@Override
public void fly() {
System.out.println(name + " is flying");
}
}
```
阅读全文