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.