Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

behavior of static variable with inheritance

I am asking this question for the discussion.

Suppose i have flowing class hierarchy

    class  A
    {
    public:
         static int varr;
    }

    class B : public A
    {

    }

    Class C : public A
    {
    }

If I create the Object of B b1,b2,b3; and C c1,c2,c3; and A a1, a2;

1.will varr is shared across all the object mentioned above or there will be separate instance for different object?

2.if b1 object change the value it will be reflected for c1 object or not.

like image 453
Vikram Ranabhatt Avatar asked Apr 28 '11 10:04

Vikram Ranabhatt


People also ask

Can we use static variable in inheritance?

Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.

Is a static variable in a superclass is considered an instance variable?

This is because, static variables are shared between all objects of the same class. It is a variable which belongs to the class and not to object(instance).

Why is inheritance static?

Java Language Inheritance Static Inheritance Writing a method with the same signature as a static method in a super class appears to be a form of overriding, but really this simply creates a new function hides the other. Note that unlike normal inheritance, in static inheritance methods are not hidden.

Are static members inherited to subclass in Java justify?

Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.


1 Answers

Yes, it will be shared accross all the instance of all derived(B,C) and base class(A)..

Only one instance for a static object will be created, and at all place that object will be refered. So if you change at one place it means change will be reflected at all location where its being refered.

like image 122
vrajs5 Avatar answered Sep 24 '22 23:09

vrajs5