多态数组和对象数组例子
时间: 2023-10-26 14:03:34 浏览: 104
多态数组指的是可以存储不同类型的对象的数组,例如:
```java
Animal[] animals = new Animal[3];
animals[0] = new Cat();
animals[1] = new Dog();
animals[2] = new Bird();
for (Animal animal : animals) {
animal.makeSound();
}
```
在上面的例子中,我们创建了一个大小为3的`Animal`类型的数组,然后将三种不同类型的动物对象存储在数组中。由于`Cat`、`Dog`、`Bird`都是`Animal`的子类,因此可以将它们存储在`Animal`类型的数组中。最后,我们使用`for-each`循环遍历数组,调用每个动物的`makeSound()`方法。
对象数组指的是存储同一类型对象的数组,例如:
```java
Person[] people = new Person[3];
people[0] = new Person("John", 25);
people[1] = new Person("Mary", 30);
people[2] = new Person("Tom", 40);
for (Person person : people) {
System.out.println(person.getName() + " is " + person.getAge() + " years old.");
}
```
在上面的例子中,我们创建了一个大小为3的`Person`类型的数组,然后将三个不同的`Person`对象存储在数组中。最后,我们使用`for-each`循环遍历数组,输出每个人的姓名和年龄。
阅读全文
相关推荐
![sln](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)