简体   繁体   English

当类从抽象类扩展时,如何访问其私有变量?

[英]When a class extends from an abstract class then how to access its private variables?

I have an abstract class A and class B extends from it.I made those variables private and its fine. 我有一个抽象类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;
    }

Then I want to write the class B. 然后我要写B类。

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

I don't understand how to write a constructor for class B to access it's private variables. 我不明白如何为B类编写构造函数以访问其私有变量。 I wrote something like this and its wrong. 我写了这样的东西和它的错。

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

Can u help me to solve this with a short explanation. 您能帮我解决一下简短的解释吗?

The above should be fine, except that you have to specify a call to A 's constructor, since by constructing a B , you're also constructing an A 除了必须指定对A的构造函数的调用之外,上面的方法应该很好,因为通过构造B ,您还可以构造A

eg 例如

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

In the above you somehow have to determine how to construct an A . 在上面,您必须以某种方式确定如何构造A What values will you specify for A ? 您将为A指定什么值? You would normally pass that into the constructor for B eg 您通常会将其传递给B的构造函数,例如

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

You do not have a default constructor for class A . 您没有类A的默认构造函数。 It means you must specifies a call to A constructor from B constructor. 这意味着您必须从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;
}

If a class inherit another, when you construct the child Class an implicit call to the mother class constructor is also done. 如果一个类继承另一个类,则在构造子类时,也会对母类构造函数进行隐式调用。 Since your A does not have default constructor, it means you want to use a specific one, so you must call it explicitly. 由于您的A没有默认构造函数,这意味着您要使用特定的构造函数,因此必须显式调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM