简体   繁体   中英

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.

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.

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

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 . What values will you specify for A ? You would normally pass that into the constructor for B eg

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 . It means you must specifies a call to A constructor from B constructor.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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