定义超类,并通过继承定义子类,在子类中重写方法代码
时间: 2023-12-27 09:02:55 浏览: 35
以下是一个简单的 Java 代码示例,演示了如何定义超类 `Animal`,并通过继承定义子类 `Cat` 和 `Dog`,在子类中重写 `Animal` 类中的 `makeSound()` 方法:
```
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows.");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks.");
}
}
```
在上述代码中,`Animal` 类定义了一个 `makeSound()` 方法,`Cat` 类和 `Dog` 类都继承了 `Animal` 类,并且在子类中重写了 `makeSound()` 方法。
当我们创建 `Cat` 类和 `Dog` 类的对象,并调用它们的 `makeSound()` 方法时,会优先执行子类中的方法。
例如:
```
public static void main(String[] args) {
Animal cat = new Cat();
Animal dog = new Dog();
cat.makeSound(); // 输出 "The cat meows."
dog.makeSound(); // 输出 "The dog barks."
}
```
在上述代码中,我们创建了一个 `Cat` 类对象和一个 `Dog` 类对象,并将它们都赋值给了 `Animal` 类型的变量。当我们调用它们的 `makeSound()` 方法时,会根据实际类型来执行相应的方法,输出各自的声音。
相关推荐
![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_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)