gpt4 book ai didi

java - 如何访问子类对象中抽象类中私有(private)属性的值?

转载 作者:行者123 更新时间:2023-11-30 11:26:20 25 4
gpt4 key购买 nike

我正在上 Java 类(class),这个问题与我要完成的练习之一有关。我正在尝试打印出从抽象父类(super class)的 2 个子类创建的对象数组的内容。我能够创建对象并将它们存储在一个数组中,但是当我打印出数组的内容时,我只能获得父类(super class)的“age”和“weight”属性的最后一个实例。如您所见,它们是私有(private)属性。有没有办法在创建对象时访问这些属性的值?我读了很多书,但我很困惑我是否能做到,如果我能,那么怎么做?我的代码:

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");

我的理解是我只能通过方法访问父类(super class)的属性。当我在 toString() 中使用 getAge() 和 getWeight() 方法时,我没有获得为每个对象输入的值,只有属性具有的最后一个值。任何帮助将不胜感激。干杯。

最佳答案

不要对年龄和体重使用静态变量:

private static int age;
private static double weight;

静态变量的值对于该类型的所有对象都是相同的,因为这些变量是变量,而不是实例变量。这些人应该是实例 或非静态字段,这将使它们对于此类的每个实例(或子类的实例)都是唯一的。

然后在您的子类中,去掉这些遮蔽变量,因为它们会遮蔽父类中同名的字段:

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。

关于java - 如何访问子类对象中抽象类中私有(private)属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com