Java and inherited static members [duplicate]

2019-01-18 11:01发布

This question already has an answer here:

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?

9条回答
闹够了就滚
2楼-- · 2019-01-18 11:29

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.

查看更多
祖国的老花朵
3楼-- · 2019-01-18 11:29

It is possible, but not using a single counter. You'll need a counter per subtype. For example, something like the following:

private static Map<Class<?>, Integer> counters = new HashMap<>();

Parent() {
     Integer curID = counters.get(this.getClass());
     if (curID == null) {
         curID = 0;
     }
     ID = curID;
     curID++;
     counters.put(this.getClass(), curID);
}

Beware: the above is not thread-safe. But your initial code isn't either...

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-18 11:31

You are using a static variable

  • There are no copies of static variable for different objects,
  • There will be only on copy of static variable and it will be shared for all the instances

Regarding static variable inheritance, They are not inheritd at all

So even if you say

r1.curID;
t1.curID;

It will mean the same thing, i.e. Parent.curID

When you are changing a static variable from the instance of the class, and if another instance is accessing that variable, it will get the changed value as its a shared variable

查看更多
登录 后发表回答