Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Field Hiding

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 class with a protected static boolean field = false and a sub class which has a boolean field with the same name but is not static and set to true.

If I had this code:

Superclass d = new subclass();

what would be the value of the boolean field in the superclass and the boolean field in the subclass? Does subclass field stay as false after the assignment above?

like image 750
daveb Avatar asked Dec 04 '22 03:12

daveb


1 Answers

  • 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
        }
    }
    
like image 67
Paul Vargas Avatar answered Dec 09 '22 16:12

Paul Vargas