使用继承的方式实现一个多态程序
时间: 2024-05-12 16:19:33 浏览: 16
多态是指同一种操作作用于不同的对象上面,可以产生不同的执行结果。在面向对象编程中,多态是指同一种类型的对象在不同的情况下有不同的表现形式和状态。
下面我们使用继承的方式实现一个多态程序:
首先定义一个父类Animal,包含两个方法:eat()和sleep()。
```
class Animal {
public void eat() {
System.out.println("Animal is eating.");
}
public void sleep() {
System.out.println("Animal is sleeping.");
}
}
```
然后定义两个子类:Cat和Dog,分别继承Animal类并重写eat()方法。
```
class Cat extends Animal {
public void eat() {
System.out.println("Cat is eating fish.");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog is eating bone.");
}
}
```
最后在主方法中创建Animal、Cat和Dog对象,调用它们的eat()方法,观察执行结果。
```
public static void main(String[] args) {
Animal animal = new Animal();
Cat cat = new Cat();
Dog dog = new Dog();
animal.eat();
cat.eat();
dog.eat();
}
```
执行结果如下:
```
Animal is eating.
Cat is eating fish.
Dog is eating bone.
```
可以看到,Animal、Cat和Dog对象都调用了eat()方法,但是输出的结果不同,这就是多态的体现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)