Reputation: 151
A question about inheritance in java...
class Base {
private int val = 10;
}
class Derive extends Base{
public void setVal(int value) {
super.val = value;
}
}
Since we can change the private
field in super class using super
keyword in the subclass, why should we use protected
to declare fields in super class?
Upvotes: 0
Views: 367
Reputation: 164
super is an reference variable which is used to call parents constructor.
Upvotes: 0
Reputation: 164
Check your code you can never access private out side the class even if you have inherited that class.
Upvotes: 0
Reputation: 1499770
You can't do that. The code you've given doesn't compile, unless Derive
is declared as a nested class within Base
(which is a pretty rare case).
You should be getting an error like this:
error: val has private access in Base
Upvotes: 4