java编码实现动物世界的继承关系
时间: 2024-10-11 17:13:40 浏览: 29
在Java中,我们可以创建一个动物界(Animal)作为父类,然后通过继承让各个具体的动物种类如猫(Cat)、狗(Dog)等成为它的子类。下面是一个简单的例子:
```java
// 父类 Animal
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
// 定义通用的行为,比如叫唤
public void makeSound() {
System.out.println("动物叫了声");
}
}
// 子类 Cat 和 Dog 继承自 Animal
class Cat extends Animal {
public Cat(String name) {
super(name);
}
// 重写父类的方法,提供猫的叫声
@Override
public void makeSound() {
System.out.println("喵~");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
// 重写父类的方法,提供狗的叫声
@Override
public void makeSound() {
System.out.println("汪汪~");
}
}
// 主函数测试
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat("花花"); // 动物引用指向猫实例
Animal animal2 = new Dog("豆豆"); // 动物引用指向狗实例
animal1.makeSound(); // 输出 "喵~"
animal2.makeSound(); // 输出 "汪汪~"
}
}
```
在这个例子中,`Cat` 和 `Dog` 都继承了 `Animal` 类,并覆盖了 `makeSound()` 方法来体现多态性,即虽然它们都是动物,但各自的叫声却各不相同。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)