java如何实现多态
时间: 2024-01-18 12:02:30 浏览: 34
Java实现多态的方式是通过继承和方法重写来实现的。下面是一个简单的示例代码:
```java
class Animal {
public void sound() {
System.out.println("动物发出声音");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("猫发出喵喵的声音");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("狗发出汪汪的声音");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat(); // 使用父类的引用指向子类的对象
Animal animal2 = new Dog(); // 使用父类的引用指向另一个子类的对象
animal1.sound(); // 调用子类的重写方法
animal2.sound(); // 调用另一个子类的重写方法
}
}
```
在上面的代码中,Animal是一个父类,Cat和Dog是Animal的子类。通过使用父类类型的引用指向子类的对象,可以实现多态。在运行时,根据实际对象的类型,调用对应的方法。这里调用的是子类中重写(覆盖)了父类方法的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)