ree*_*ing 2 java parameters constructor superclass
我对如何从新对象实例中获取参数也流入超类以更新超类中的私有字段感到困惑。
所以我在一个高级Java课上,并且我的作业需要一个“ Person”超级类和一个扩展“ Person”的“ Student”子类。
Person类存储学生姓名,但它是Student类的构造函数,它接受Person名称。
假设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.
}
}
Run Code Online (Sandbox Code Playgroud)
在允许我对Person的超类进行多少更改方面,有关家庭作业的说明有些含糊,因此,如果大家都认为,行业认可的良好解决方案涉及更改超类,我会这样做。
我看到的一些可能的示例是使Person类中的私有vars受“保护”,或者在person类中添加setMethods(),然后在子类中调用它们。
我也接受关于如何将子类构造函数参数传递给超类的一般概念教育,如果可能的话,可以在代码的构造函数部分正确进行操作。
最后,我确实进行了搜索,但是大多数类似的问题都是非常具体且复杂的代码。。。。。。。。。。。。。。。。。。。。。。。。。非常抱歉阅读上面的内容。
谢谢大家
首先,您需要为定义一个构造函数Person:
public Person(String startName, int startDollars, boolean startMood)
{
name = startName;
dollars = startDollars;
mood = startMood;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以Student使用super(...)以下方法从构造函数中传递数据:
public Student(String startName, int startDollars, boolean startMood, String major)
{
super(startName, startDollars, startMood);
. . .
}
Run Code Online (Sandbox Code Playgroud)
另外,您可以在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.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14568 次 |
| 最近记录: |