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?
You can’t do that. The code you’ve given doesn’t compile, unless
Deriveis declared as a nested class withinBase(which is a pretty rare case).You should be getting an error like this: