Reputation:
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.
Upvotes: 2
Views: 104
Reputation: 7862
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.
Upvotes: 1
Reputation: 272237
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
e.g
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 e.g.
public B(int fee, int goals, String name, String location) {
super(name, location);
this.fee= fee;
this.goals=goals;
}
Upvotes: 5