1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
yesilupper
  • 813
  • 1
  • 7
  • 7
  • Please post a link to that question – adarshr Jul 28 '11 at 21:21
  • fields are not overridden. They are just hidden. – Kal Jul 28 '11 at 21:24
  • thanks adarshr http://stackoverflow.com/questions/6851612/java-access-modifiers-and-overriding – yesilupper Jul 29 '11 at 12:29
  • updated the title of previous question to reflect methods() as hiding fields is shunned it seem: http://stackoverflow.com/questions/6851612/java-access-modifiers-and-overriding-methods – yesilupper Jul 29 '11 at 13:15
  • It appears that it's not about hiding/overriding when it comes to access modifiers. I just tried hiding methods and the same visibility rules apply. I still can't reduce the visibility on an inherited static method(). What's the difference between fields and methods()? – yesilupper Jul 29 '11 at 13:19
  • Possible duplicate of [When overriding a method, why can I increase access but not decrease it?](https://stackoverflow.com/questions/6851612/when-overriding-a-method-why-can-i-increase-access-but-not-decrease-it) – double-beep May 12 '19 at 18:18
  • @double-beep That question is about methods, this one is about fields. It is not a duplicate. – Mark Rotteveel May 13 '19 at 15:43

2 Answers2

3

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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
}
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • Of course you can make a field private. I think you mean you can't change the access of a field in the base class by providing a private field in the subclass... but I suggest you clarify your answer. – Jon Skeet Jul 28 '11 at 21:31