编写一个程序实现方法的覆盖
时间: 2024-02-01 18:13:19 浏览: 28
方法的覆盖是指在子类中定义了与父类相同名称和参数列表的方法,以覆盖父类中的方法。
以下是一个简单的示例程序,演示了方法的覆盖:
```
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Program {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // 输出 "The animal makes a sound"
Dog dog = new Dog();
dog.makeSound(); // 输出 "The dog barks"
}
}
```
在这个示例程序中,我们定义了一个 `Animal` 类和一个 `Dog` 类,`Dog` 类继承自 `Animal` 类。`Animal` 类中有一个名为 `makeSound` 的方法,`Dog` 类重写了这个方法,并且在子类中实现了一个新的方法体。
在 `main` 方法中,我们创建了一个 `Animal` 对象和一个 `Dog` 对象,并且分别调用了它们的 `makeSound` 方法。当调用 `Animal` 对象的 `makeSound` 方法时,输出的是 "The animal makes a sound",而调用 `Dog` 对象的 `makeSound` 方法时,输出的是 "The dog barks"。这是因为 `Dog` 类重写了 `Animal` 类中的 `makeSound` 方法,所以在 `Dog` 类中调用 `makeSound` 方法时,执行的是 `Dog` 类中实现的方法体,而不是 `Animal` 类中的方法体。
这就是方法的覆盖,子类重写父类中的方法,并且在子类中实现新的方法体。当我们调用子类对象的方法时,执行的是子类中的方法体,而不是父类中的方法体。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)