java创建抽象类animal,包含一个抽象方法eat()。 创建animal的子类dog,实现父类中的抽象方法eat,输出“现在是狗狗的eat方法” 创建animal的子类horse,实现父类中的抽象方法eat,输出“现在是马的eat方法” 创建animal的子类rabbit,实现父类中的抽象方法eat,输出“现在是兔子的eat方法” 并分别创建dog\horse\rabbit的对象且调用其eat方法。
时间: 2024-03-21 13:39:54 浏览: 38
好的,以下是Java代码实现:
```java
// 抽象类 Animal
public abstract class Animal {
public abstract void eat();
}
// Dog 类继承 Animal 抽象类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("现在是狗狗的eat方法");
}
}
// Horse 类继承 Animal 抽象类
public class Horse extends Animal {
@Override
public void eat() {
System.out.println("现在是马的eat方法");
}
}
// Rabbit 类继承 Animal 抽象类
public class Rabbit extends Animal {
@Override
public void eat() {
System.out.println("现在是兔子的eat方法");
}
}
// 测试
public class Test {
public static void main(String[] args) {
Animal dog = new Dog();
Animal horse = new Horse();
Animal rabbit = new Rabbit();
dog.eat(); // 现在是狗狗的eat方法
horse.eat(); // 现在是马的eat方法
rabbit.eat(); // 现在是兔子的eat方法
}
}
```
以上代码中,我们定义了一个抽象类 Animal,其中包含了一个抽象方法 eat。然后创建了三个 Animal 的子类 Dog、Horse、Rabbit 分别继承了 Animal 抽象类,并实现了其中的抽象方法 eat。在 Test 类中,我们创建了 Dog、Horse、Rabbit 的实例对象,并调用了它们的 eat 方法。运行结果会分别输出对应子类中的 eat 方法的输出。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)