【问题标题】:When a class extends from an abstract class then how to access its private variables?当一个类从抽象类扩展时,如何访问它的私有变量?
【发布时间】:2014-11-15 14:58:19
【问题描述】:

我有一个抽象类 A 和类 B 扩展自它。我将这些变量设为私有并且很好。

public abstract class A  {
    private String name;
    private String location;

public A(String name,String location) {
        this.name = name;
        this.location = location;
}
 public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }


    public String getLocation() {
        return location;
    }

那我想写B类。

public class B extends A{
private int fee;
private int goals;   // something unique to class B

我不明白如何为 B 类编写构造函数来访问它的私有变量。 我写了这样的东西,它是错误的。

    B(int fee, int goals){
       this.fee= fee;
       this.goals=goals;
     }

你能帮我用一个简短的解释解决这个问题吗?

【问题讨论】:

标签: java constructor abstract-class


【解决方案1】:

上面应该没问题,除了你必须指定一个对A的构造函数的调用,因为通过构造一个B,你在构造一个A

例如

public B(int fee, int goals) {
    super(someName, someLocation); // this is calling A's constructor
    this.fee= fee;
    this.goals=goals;
}

在上面你必须以某种方式确定如何构造一个A。您将为 A 指定什么值?您通常会将其传递给 B 的构造函数,例如

public B(int fee, int goals, String name, String location) {
    super(name, location);
    this.fee= fee;
    this.goals=goals;
}

【讨论】:

  • 感谢布赖恩,现在我明白了,现在可以正常工作了。非常感谢
【解决方案2】:

您没有类A 的默认构造函数。这意味着您必须指定从B 构造函数调用A 构造函数。

public B(String name, String location int fee, int goals) {
    super(name, location); // this line call the superclass constructor
    this.fee = fee;
    this.goals = goals;
}

如果一个类继承另一个类,当你构造子类时,也会隐式调用母类构造函数。 由于您的A 没有默认构造函数,这意味着您要使用特定的构造函数,因此必须显式调用它。

【讨论】:

  • 非常感谢安东尼,我知道了。
猜你喜欢
  • 2017-03-08
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2019-08-28
相关资源
最近更新 更多