我正在学习 Java 课程,这个问题与我要完成的一个练习有关。我正在尝试打印从抽象超类的 2 个子类创建的对象数组的内容。我能够创建对象并将它们存储在一个数组中,但是当我打印出数组的内容时,我只能获得超类的“年龄”和“体重”属性的最后一个实例。如您所见,它们是私有属性。有没有办法在创建对象时访问这些属性的值?我已经阅读了相当多的内容,但我很困惑我是否可以做到,如果可以,那该怎么做?我的代码:
public abstract class Parent {
private static int age;
private static double weight;
public Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public static int getAge() {
return age;
}
public static double getWeight() {
return weight;
}
}
public class Child1 extends Parent {
private String name, owner, petInfo;
protected int age;
protected double weight;
public Child1(int age, double weight, String name, String owner) {
super(age, weight);
this.name = name;
this.owner = owner;
}
public String toString() {
petInfo = "Pet's name: " + this.getName() + "\nPet's age: " + getAge() + " years\nPet's weight: " + getWeight() + " kilos\nOwner's name: " + this.getOwner();
return petInfo;
}
}
public class Child2 extends Parent {
public String wildInfo;
public Child2(int age, double weight) {
super(age, weight);
}
public String toString() {
wildInfo = "The wild animal's age: " + getAge() + "\nThe wild animal's weight: " + getWeight();
return wildInfo;
}
}
public class Console {
public static void main(String[] args) {
Parent ref[] = new Parent[5];
for(i = 0; i < 5; i++) {
//user input here
Child1 pet = new Child1(age, weight, name, owner);
ref[i] = pet;
//more user input
Child2 wild = new Child2(age, weight);
ref[i] = wild;
}
//print contents of array
for(Parent item : ref)
System.out.println("\n" +item.toString()+ "\n");
我的理解是,我只能通过方法访问超类的属性。当我在 toString() 中使用 getAge() 和 getWeight() 方法时,我没有得到为每个对象输入的值,只有属性具有的最后一个值。任何帮助将不胜感激。干杯。