我对如何从新对象实例获取参数以也流入超类以更新超类中的私有字段感到困惑。
所以我在一个高级Java类中,我有一个需要“Person”超类和扩展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 的超类进行多少更改,家庭作业的说明有点模糊,所以如果你们都相信一个良好的、可靠的行业接受的解决方案涉及更改超类,我会这样做。
我看到的一些可能的例子是让 Person 类中的私有变量“受保护”,或者在 person 类中添加 setMethods() 然后在子类中调用它们。
我也对如何将子类构造函数参数传递给超类的一般概念教育持开放态度……如果可能的话,在代码的构造函数部分正确地做。
最后,我确实搜索过,但大多数类似的问题都是非常具体和复杂的代码......我找不到像上面的例子那样直接的东西......同样由于某种原因,论坛帖子没有将我所有的代码聚集在一起对于上面令人困惑的阅读,我们深表歉意。
谢谢大家。