使用java实现下面功能:生成一个动物类:其中包含一个方法,可以输出动物的叫声; 设计两个子类:猫类和狗类分别继承于动物类;
时间: 2024-02-17 16:04:57 浏览: 34
可以使用如下代码实现该功能:
```
// Animal.java
public class Animal {
public void makeSound() {
System.out.println("动物发出叫声!");
}
}
// Dog.java
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("汪汪汪!");
}
}
// Cat.java
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("喵喵喵!");
}
}
// Test.java
public class Test {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound(); // 输出:汪汪汪!
animal2.makeSound(); // 输出:喵喵喵!
}
}
```
其中,Animal 类是一个基类,包含一个 makeSound() 方法,可以输出动物的叫声。Dog 和 Cat 类分别继承于 Animal 类,并覆盖了 makeSound() 方法,分别输出不同的叫声。
在 Test 类中,我们定义了两个 Animal 类型的变量,分别指向 Dog 和 Cat 的实例。由于 Dog 和 Cat 都是 Animal 的子类,因此它们可以被当作 Animal 类型来使用。调用它们的 makeSound() 方法时,会根据实际的类型而执行不同的方法,输出不同的声音。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](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)