我正在用Java上一堂课,这个问题与我要完成的一项练习有关。我正在尝试打印从抽象超类的2个子类创建的对象数组的内容。我能够创建对象并将它们存储在数组中,但是当我打印出数组的内容时,我只能获得超类的“ age”和“ weight”属性的最后一个实例。如您所见,它们是私有属性。创建对象时,是否可以访问这些属性的值?我已经做了大量的阅读工作,但是我对是否可以阅读感到困惑,如果可以的话,那又如何呢?我的代码:
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()方法时,我没有得到为每个对象输入的值,只有属性具有的最后一个值。任何帮助将不胜感激。干杯。
不要为年龄和体重使用静态变量:
private static int age;
private static double weight;
对于此类型的所有对象,静态变量的值都相同,因为这些变量是类变量,而不是实例变量。这些家伙应该是实例或非静态字段,这将使它们对于此类的每个实例(或子类的实例)都是唯一的。
然后在您的Child类中,摆脱这些阴影变量,因为它们将对Parent类中类似命名的字段进行阴影:
public class Child1 extends Parent {
private String name, owner, petInfo;
protected int age; // ***** get rid of, since it shadows
protected double weight; // ***** get rid of, since it shadows
相反,无论您在何处使用这些控件,都应使用Child类中的getter和setter方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句