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..
Static variables are not inherited in java. You varibale static String a is static which associates it to a class. Java inheritance doesn't work with static variables.
If you absolutely want the superclass variable you could use:
System.out.println(super.a);
Here is the inheritance what you probably wish to see:
abstract class A {
String a = "superclass";
abstract void test();
}
class B extends A {
void test() {
System.out.println(a); // Output superclass
}
}
I remove the static identifier and removed the subclass's implementation of variable a. If you run this you'll get superclass as output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With