I have a code in which I expect the output to be different from the actual output.. As static variables are reference based, I expect the output to be "superclass" but what I am getting is "subclass".. Code:
class TestClass {
public static void main(String args[] ) throws Exception {
A b = new B(); // Since the reference is A, "superclass" should be the output
b.test();
}
}
abstract class A{
static String a = "superclass";
abstract void test();
}
class B extends A{
static String a = "subclass";
void test(){
System.out.println(a); // Output subclass
}
}
Please tell me where am I wrong..
System.out.println(b.a)it would indeed print "superclass" as the variablebhas typeA(and thusb.ais same asA.afor static variables). You're referring to the variableafrom a method inside classB, so it's equivalent toB.a.