gpt4 book ai didi

java - 如何将子类参数传递给父类(super class)私有(private)变量?

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

我对如何从新对象实例获取参数也流入父类(super class)以更新父类(super class)中的私有(private)字段感到困惑。

所以我在高级 Java 类(class)中,我的家庭作业需要一个“Person”父类(super class)和一个扩展 Person 的“Student”子类。

Person 类存储学生姓名,但接受 Person 姓名的是 Student 类构造函数。

假设 Person 中没有方法来更新变量方法...比如 subClassVar = setSuperClassVar();

例如:

public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
}

class Student extends Person //I also have a tutor class that will extend Person as well
{
private String degreeMajor //holds the var for the student's major they have for their degree

Public Student(String startName, int startDollars, boolean startMood, String major)
{
degreeMajor = major; // easily passed to the Student class
name = startName; //can't pass cause private in super class?
mood = startMood; //can't pass cause private in super class?
dollars = startDollars; // see above comments
// or I can try to pass vars as below as alternate solution...
setName() = startName; // setName() would be a setter method in the superclass to...
// ...update the name var in the Person Superclass. Possible?
setMood() = startMood; // as above
// These methods do not yet exist and I am only semi confident on their "exact"...
// ...coding to make them work but I think I could manage.
}
}

家庭作业的说明在允许我对 Person 的父类(super class)进行多少更改方面有点含糊,所以如果你们都认为一个良好且可靠的行业接受的解决方案涉及更改父类(super class),我会这样做。

我看到的一些可能的例子是使 Person 类中的私有(private)变量“ protected ”或在 person 类中添加 setMethods() 然后在子类中调用它们。

我也愿意接受有关如何将子类构造函数参数传递给父类(super class)的一般概念教育...如果可能的话,请在代码的构造函数部分正确执行此操作。

最后,我确实四处搜索,但大多数类似的问题都是非常具体和复杂的代码......我找不到像我上面的例子那样直接的东西......而且出于某种原因,论坛帖子并没有聚集所有我的代码在一起很抱歉上面的困惑阅读。

谢谢大家。

最佳答案

首先,你需要为Person定义一个构造器:

public Person(String startName, int startDollars, boolean startMood)
{
name = startName;
dollars = startDollars;
mood = startMood;
}

然后您可以使用 super(...)Student 构造函数向上传递数据:

public Student(String startName, int startDollars, boolean startMood, String major)
{
super(startName, startDollars, startMood);
. . .
}

或者,您可以在 Person 类中定义 setter,并从 Student 构造函数中调用它们。

public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance

public void setName(String name) {
this.name = name;
}
// etc.
}

关于java - 如何将子类参数传递给父类(super class)私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945320/

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