public class Animal { String[] animals = {"dog", "cat", "bird", "fish"}; public void printAnimals() { for (String animal : animals) { System.out.println(animal); } }}public class Dog extends Animal { int[] nums = {1, 2, 3, 4}; public void printNums() { for (int num : nums) { System.out.println(num); } }}public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.printAnimals(); // 输出:dog cat bird fish dog.printNums(); // 输出:1 2 3 4 }}如果这个代码中的数组是在Main中建立该如何解决
时间: 2024-03-07 22:46:45 浏览: 98
可以将数组作为参数传递给Animal和Dog类的构造函数,并在构造函数中初始化数组。代码示例:
```
public class Animal {
String[] animals;
public Animal(String[] animals) {
this.animals = animals;
}
public void printAnimals() {
for (String animal : animals) {
System.out.println(animal);
}
}
}
public class Dog extends Animal {
int[] nums;
public Dog(String[] animals, int[] nums) {
super(animals);
this.nums = nums;
}
public void printNums() {
for (int num : nums) {
System.out.println(num);
}
}
}
public class Main {
public static void main(String[] args) {
String[] animals = {"dog", "cat", "bird", "fish"};
int[] nums = {1, 2, 3, 4};
Dog dog = new Dog(animals, nums);
dog.printAnimals();
dog.printNums();
}
}
```
输出结果与原来的代码相同。
阅读全文