-1
class Test {
public static final String FOO = "foo";
public static void main(String[] args) {
Test b = new Test();
Sub s = new Sub();
System.out.print(Test.FOO);           /* Prints foo */
System.out.print(Sub.FOO);            /* Prints bar */
System.out.print(b.FOO);              /* Prints foo */
System.out.print(s.FOO);              /* Prints bar */
 System.out.print(((Test)s).FOO);     /* Prints foo but Why?*/ 
 } }
 class Sub extends Test {public static final String FOO="bar";}

I was reading about Inheritance and i found out that even when you cast a SUB CLASS object to PARENT class and try to call a overridden method using that object (see here), the SUBCLASS method will be called.

But here in my Question why the Parent Class variable value is being printed even when the object TYPE is of Class Sub.?

Community
  • 1
  • 1

1 Answers1

4

Static members are resolved by the type of the expression that is used to reference it, if you use <expression>.staticMember.

In this case ((Test)s) is an expression of type Test and this is why Test.FOO is referenced in ((Test)s).FOO.

Note that it's bad practice to use instances to reference static members, since this just leads to confusion. Always using <ClassName>.staticMember avoids this kind of confusion, i.e. use

Test.FOO

or

Sub.FOO
fabian
  • 80,457
  • 12
  • 86
  • 114