I was just playing around with static and inheritance to see what can and cannot be done. I have read before, that static methods cannot be overwritten, they can simply be hidden. That is why I tried to see what applies to static members. Here is some simple Test code:
public class ParentClass {
public static String x;
{ x = "In ParentClass"; }
}
public class ChildClass extends ParentClass {
{ x = "In ChildClass"; }
}
Now when I printed x called from objects, everything went as expected:
ParentClass parentClassReference = new ParentClass();
System.out.println(parentClassReference.x); // prints: "In ParentClass"
parentClassReference = new ChildClass();
System.out.println(parentClassReference.x); // prints: "In ChildClass"
Even the trivial call to x from a child class object:
ChildClass childClassReference = new ChildClass();
System.out.println(childClassReference.x); // prints: "In ChildClass"
Now, when I call the static member, like it is supposed to be done, it gets weird:
System.out.println(ChildClass.x); // prints: "In ChildClass" (Ok, so far.)
System.out.println(ParentClass.x); // prints: "In ChildClass" (This is unexpected.)
I have no explanation for this behaviour. In the context of Overriding vs. Hiding (Code Ranch) It seemed more likely that the calls through objects shouldn’t work as expected, but the calls through class names should.
I am confused. Who can help?
Your code is very strange… but the results are exactly as I’d expect.
You need to understand three things:
xvariable here. Whether you reference it asChildClass.xorParentClass.x, it’s the same variablechildClassReference.xis equivalent toChildClass.x, which is actually compiled asParentClass.x. Good IDEs will warn you of this sort of thing – it produced confusing code.The code you’ve written which sets the value of
xis only executed based on a constructor call. Basically it’s equivalent to:Fundamentally, you shouldn’t be trying to achieve any kind of polymorphism through static members. It doesn’t work, and attempts to fake it will not end happily.