Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and inherited static members [duplicate]

Suppose i have the below class:

class Parent
{
    private int ID;
    private static int curID = 0;

    Parent()
    {
         ID = curID;
         curID++;
    }
}

and these two subclasses:

class Sub1 extends Parent
{
    //...
}

and

class Sub2 extends Parent
{
    //...
}

My problem is that these two subclasses are sharing the same static curID member from parent class, instead of having different ones.

So if i do this:

{
    Sub1 r1 = new Sub1(), r2 = new Sub1(), r3 = new Sub1();
    Sub2 t1 = new Sub2(), t2 = new Sub2(), t3 = new Sub2();
}

ID's of r1,r2,r3 will be 0,1,2 and of t1,t2,t3 will be 3,4,5. Instead of these i want t1,t2,t3 to have the values 0,1,2, ie use another copy of curID static variable.

Is this possible? And how?

like image 747
Fr0stBit Avatar asked Jun 18 '13 14:06

Fr0stBit


People also ask

Can static members be inherited in Java?

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.

Can we inherit static members?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Are static Fields inherited?

Constructors, static initializers, and instance initializers are not members and therefore are not inherited.

Do subclasses inherit static methods?

Note that unlike normal inheritance, in static inheritance methods are not hidden. You can always call the base sayHello method by using BaseClass. sayHello() . But classes do inherit static methods if no methods with the same signature are found in the subclass.


1 Answers

While static fields/methods are inherited, they cannot be overridden since they belong to the class that declares them, not to the object references. If you try to override one of those, what you'll be doing is hiding it.

like image 103
Luiggi Mendoza Avatar answered Oct 14 '22 23:10

Luiggi Mendoza