Reputation: 843
This is a follow-up to the question: "java access modifiers and overriding". The former generally deals with Java methods however. Why the flexibility with Java fields? We can narrow or widen the visibility with their respect in an inherited class whereas can't with an 'overridden' nor 'hidden' method.
Upvotes: 1
Views: 1268
Reputation: 43504
why the flexibility with java fields
You cannot make a field in another class go private by extending it. When you make a new field in a sub class you are just hiding the super class field.
class Base {
protected int x;
}
class Ext extends Base {
private int x; // not the same as Base.x
}
Upvotes: 2
Reputation: 1503260
You never override fields to start with - you're always hiding them. Fields aren't polymorphic... in other words, if you write:
Superclass x = new Subclass();
System.out.println(x.field);
and both Superclass
and Subclass
declare a field called field
, it will always use the superclass one anyway, because that's all the compiler can "see".
Personally I try to keep my variables private anyway...
Upvotes: 3