私は Java のクラスを受講していますが、この質問は私が完了する予定の演習の 1 つに関連しています。抽象スーパークラスの 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() メソッドを使用すると、各オブジェクトに入力された値が取得されず、属性の最後の値のみが取得されます。どんな助けでも大歓迎です。乾杯。