1

I have a static variable in my Base123 class

class Base123 {
    public static int statvar;
}

and I have a derived class, Inheritance111, which extends Base123

public class Inheritance111 extends Base123 {

    public static void main(String[] args) {
        System.out.println(Inheritance111.statvar);
        System.out.println(Base123.statvar);
        Base123.statvar=10;
        System.out.println(Inheritance111.statvar);
        System.out.println(Base123.statvar);
        System.out.println(statvar);
        Inheritance111.statvar=20;
        System.out.println(Inheritance111.statvar);
        System.out.println(Base123.statvar);
        System.out.println(statvar);
    }
}

I obtained the output for above code as :

0 0 10 10 10 20 20 20

For one class, the static variable is shared across all the objects of the class. But when a class is extended, is the inherited variable in the subclass also the same variable? As the changes made using

Inheritance111.statvar=20;

is changing the value of Base123.statvar.

8
  • static variables are not inherited. doesn't mean it can't be accessed. have you tried to do it like that? what result did you get? Commented Nov 26, 2018 at 11:22
  • 1
    Static variable is shared across all the objects of that class since it belong to the class information. Commented Nov 26, 2018 at 11:24
  • @Stultuske If I give System.out.println(statvar); I see the value of the static variable from inside the Derived class. Commented Nov 26, 2018 at 11:29
  • @Stultuske how would you call this then? sharing between classes? Commented Nov 26, 2018 at 11:42
  • @Eugene why would I have to give a name to it? static members are not inherited. that doesn't mean they can't be used. that does mean, however, that when they're re-defined in the subclass, they don't overwrite, but hide the original. Commented Nov 26, 2018 at 12:16

1 Answer 1

1

Yes it refers to same variable as Super class even if you call variable from sub class like Inheritance111.statvar=20;.
You can refer to this JavaDoc static fields

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.