【问题标题】:how do I pass subclass parameters into the superclass private variables?如何将子类参数传递给超类私有变量?
【发布时间】: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


【解决方案1】:

首先,你需要为Person定义一个构造函数:

public Person(String startName, int startDollars, boolean startMood)
{
    name = startName;
    dollars = startDollars;
    mood = startMood;
}

然后您可以使用super(...) 从Student 构造函数向上传递数据:

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.
}

【讨论】:

  • 老兄...基本的亲爱的 watson...TYVM,提出直接问题并获得直接答案真是令人耳目一新。我将继续编码。
猜你喜欢
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2013-02-25
  • 2014-09-12
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多