【发布时间】:2012-10-18 00:10:14
【问题描述】:
我对如何从新对象实例获取参数以也流入超类以更新超类中的私有字段感到困惑。
所以我在学习高级 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(),然后在子类中调用它们。
我也愿意接受关于如何将子类构造函数参数传递给超类的一般概念教育......如果可能的话,请在代码的构造函数部分正确执行。
最后,我确实搜索过,但大多数类似的问题都是非常具体和复杂的代码......我找不到像上面的例子那样直接的东西......同样由于某种原因,论坛帖子没有聚集所有我的代码在一起很抱歉上面的混乱阅读。
谢谢大家。
【问题讨论】:
-
超类 (
Person) 构造函数是什么样的?Person有设置这些private字段的方法吗?
标签: java parameters constructor superclass