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

查看:33
本文介绍了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 的 ID 为 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天全站免登陆