Java Field Hiding

后端 未结 3 546
长发绾君心
长发绾君心 2020-12-10 19:57

I was wondering what it means to say a field is hidden between 2 java classes and what it means when running code in terms of resulting output?

I have an abstract c

相关标签:
3条回答
  • 2020-12-10 20:14

    static members are never overridden (and certainly not by non-static members). And since you should access them like this: ClassName.member there is also no need to worry about hiding them.

    In your case, you would access the Superclass field like this: Superclass.field. And the field of a Subclass instance like this: subclass.field. If you have, however a Subclass instance in a Superclass variable like above, this code: d.field will access the static field defined in Superclass, which will be false in your case.

    But this does not change the value of the Subclass instance, it just accesses the "wrong" member! You can verify this by putting the instance in d back into a Subclass variable and reading field again.

    0 讨论(0)
  • 2020-12-10 20:14

    what would be the value of the boolean field in the superclass and the boolean field in the subclass?

    The value of field variable in superclass will remain false and the value of field in the subclass will remain true.

    Does subclass field stay as FALSE after the assignment above?

    No. You cannot override static variables in Java. What essentially happens is the definition in the sub class hides the variable declared in the super class.

    For a nice example and explanation, see SO Question

    I also suggest you try it out yourself to see what happens.

    0 讨论(0)
  • 2020-12-10 20:32
    • Java Language Specification

      If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.

      A hidden field can be accessed by using a qualified name if it is static, or by using a field access expression that contains the keyword super or a cast to a superclass type.

      See more in http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html

    • Example Code

      class A {
          static int field;
      }
      class B extends A {
          int field;
          void doSomething() {
              System.out.println(super.field); // From A
              System.out.println(field); // From B
          }
      }
      class Main {
          public static void main(String[] args) {
              B b = new B();
              System.out.println(b.field); // From B
              System.out.println(((A) b).field); // From A
              System.out.println(A.field); // From A
          }
      }
      
    0 讨论(0)
提交回复
热议问题