Reputation: 1642
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?
Upvotes: 3
Views: 106
Reputation: 1500495
Your code is very strange... but the results are exactly as I'd expect.
You need to understand three things:
x
variable here. Whether you reference it as ChildClass.x
or ParentClass.x
, it's the same variablechildClassReference.x
is equivalent to ChildClass.x
, which is actually compiled as ParentClass.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 x
is only executed based on a constructor call. Basically it's equivalent to:
public class ParentClass {
public static String x;
public ParentClass() {
x = "In ParentClass";
}
}
public class ChildClass extends ParentClass {
public ChildClass() {
x = "In ChildClass";
}
}
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.
Upvotes: 4