Reputation: 1811
class Super {
protected int a;
protected Super(int a) { this.a = a; }
}
class Sub extends Super {
public Sub(int a) { super(a); }
public Sub() { this.a = 5; }
}
public Sub() { this.a = 5; }
this.a=5 doesn't work. Why is this so? Protected and public members should be inherited.
Upvotes: 0
Views: 2112
Reputation: 3138
What does not work? Works for me...
What you do not have is a default constructor - in public Sub() {this.a = 5; }
the parent default constructor is called, which you have not provided. If I compiler your code I get:
cannot find symbol constructor Super()
So you either have to have a default constructor or do: public Sub() { super(5); }
Upvotes: 0
Reputation: 38345
Your parameterless constructor in Sub
is attempting to implicitly invoke a parameterless constructor in Super
which doesn't exist, which is (I assume) why you're getting a compile error.
Upvotes: 0
Reputation: 258548
The problem isn't that you access the variable, but that you don't call the base constructor:
class Super {
protected int a;
protected Super(int a) { this.a = a; }
}
class Sub extends Super {
public Sub(int a) { super(a); }
public Sub() {
super(0); // <-- call base constructor
this.a = 5;
}
}
This happens because you didn't define a default constructor for Super
, so derived classes don't know which constructor to call if you're not specifying one.
Upvotes: 9