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