Reputation: 1854
I have the following code and it will not compile.
public class P {
private int num;
P(int n) {
this.num = n;
}
}
public class Q extends P {
private int i;
public Q() {
i = 0;
}
}
Fix the second method so that it can compile.
Upvotes: 1
Views: 207
Reputation: 504
In the code the compiler write the super() keyword in the Q class that time control will go the P class and it call the constructor, but P class has a parameter constructor.so you can add super() keyword with the any number because P class constructor has a parameter of int type.
class P {
private int num;
P(int n) {
this.num = n;
}
}
public class Q extends P {
private int i;
public Q() {
super(20);
i = 0;
}
}
Upvotes: 0
Reputation: 129477
Invoke the super constructor:
public Q() {
super(42); // <--
i = 0;
}
You can read more about super
here.
Upvotes: 1
Reputation: 240860
You need to add default constructor in P
to make it compile
P() {
this.num = 0; // some default value
}
Upvotes: 1