Java和继承的静态成员 [英] Java and inherited static members

查看:105
本文介绍了Java和继承的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类:

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

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

以及这两个子类:

class Sub1 extends Parent
{
    //...
}

class Sub2 extends Parent
{
    //...
}

我的问题是这两个子类从
父类共享相同的静态curID成员,而不是具有不同的。

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

所以,如果我这样做:

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

r1,r2,r3的ID将为0,1,2和t1,t2,t3为3,4,5。
而不是这些我希望t1,t2,t3的值为0,1,2,即使用另一个curID静态变量副本。

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.

这是可能?如何?

推荐答案

正如其他人已经写过的那样,静态成员绑定到类,所以你需要在类级别跟踪id,例如像这样:

As others already wrote, static members are bound to the class, so you need to track the id on a class level, e.g. like this:

abstract class Parent {
    private int ID;

    Parent() {
         ID = nextId();
    }

    abstract protected int nextId();
}

class Sub1 extends Parent {
    private static int curID = 0;

    protected int nextId() {
       return curID++;
    }

    //...
}

class Sub2 extends Parent {
    private static int curID = 0;

    protected int nextId() {
       return curID++;
    }

    //...
}



<请注意,这种方法不是线程安全的 - 但问题中的代码也不是。您不能从不同的线程同时从同一个子类创建新对象。

Note that this approach is not thread safe - but neither was the code in the question. You must not create new objects from the same sub class concurrently from different threads.

这篇关于Java和继承的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆