我很困惑如何从新的对象实例获取参数也流入超类来更新超级类中的私有字段。如何将子类参数传递给超类私有变量?
所以我在一个高级的Java类,我有家庭作业,需要一个“人”超级类和扩展人的“学生”子类。
Person类存储学生名称,但它是接受Person名称的Student类构造函数。
假设没有方法在Person中进行变量方法更新... like 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类中的私人变量“protected”,或者在person类中添加setMethods(),然后在子类中调用它们。
我也接受一般概念教育,关于如何将子类contstructor参数传递给超类......并且如果可能的话,请在代码的构造函数部分执行该操作。
最后,我做了四处搜寻,但大部分类似的问题都是非常具体和复杂的代码....我无法像上面的示例那样找到任何简单的东西......也因为某些原因,论坛帖子没有聚集所有我的代码在一起,所以很抱歉上面的混淆阅读。
谢谢大家。
什么是超类('Person')构造函数的外观? 'Person'是否有设置这些'private'字段的方法? – pb2q