Search code examples
javainheritancescjp

Java inherited method question


While studying for the SCJP 6 exam, I ran into this question in a test exam:

class A{  
    private static String staticProperty = " a ";  
    String getStaticProperty() { return staticProperty; }  
}  

class B extends A {  
    private static String staticProperty = " b ";  
    public static void main(String[] args){  
        new B().go(new A());  

    }  
    void go(A t){  
        String s = t.getStaticProperty() + B.staticProperty + staticProperty + (new B().getStaticProperty());  
        System.out.println(s);  
    }  
}  

What's the output??

The output here is a b b a

I perfectly understand a b b, but don't understand the "a" at the end. If you inherit a method (in this case, B inherits getStaticProperty() from A), and that method returns a static variable from the parent (staticProperty), which you re-define in the child, you will ALWAYS use the parent static variable value??

By the way, removing the static identifier and making staticField an instance member of the classes returns the same results. Modifying access modifiers from private to public or other returns the same results. I needed to override the getStaticProperty method in order to get what I wanted to see.


Solution

  • Field access is not subject to dynamic dispatch like method access, i.e. fields cannot be overriden. This line in class A:

    String getStaticProperty() { return staticProperty; }  
    

    therefore refers to the field staticProperty in class A. Class B's field with the same name is irrelevant, or rather: it hides the superclass field, and all code in class B will use this field. Sun's Java tutorial has this to say on the matter:

    Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.