Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static variable in method overriding [duplicate]

Tags:

java

static

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..

like image 694
Handmadegifts co Avatar asked May 09 '26 01:05

Handmadegifts co


1 Answers

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.

like image 184
Shanu Gupta Avatar answered May 11 '26 15:05

Shanu Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!