我对如何从新对象实例获取参数以及流入超类以更新超类中的私有字段感到困惑。
所以我在一个高级Java类中,我的作业需要一个“Person”超类和一个扩展Person的“Student”子类。
Person类存储学生名称但是它是接受Person名称的Student类构造函数。
假设Person中没有方法来进行变量方法更新...就像subClassVar = setSuperClassVar();
EX:
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类中添加setMethods(),然后在子类中调用它们。
我也对如何将子类contstructor参数传递给超类的一般概念教育持开放态度......如果可能的话,在代码的构造函数部分执行此操作。
最后,我确实搜索过,但大多数类似的问题都是特定而且复杂的代码......我无法像上面的例子那样直截了当地找到任何东西......也出于某种原因论坛帖子没有聚集所有的我的代码在一起很抱歉上面的这个令人困惑的阅读。
谢谢大家。
答案 0 :(得分:4)
首先,您需要为Person
:
public Person(String startName, int startDollars, boolean startMood)
{
name = startName;
dollars = startDollars;
mood = startMood;
}
然后,您可以使用Student
super(...)
构造函数传递数据
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.
}