带增量字段的Instantion

时间:2013-10-05 14:37:43

标签: java

我有一个带有private int cardID字段的ServiceCard类,当我创建一个或多个ServiceCard实例时,我希望第一个实例有cardID=1,第二个实例有cardID=2等等

我尝试将cardID设为静态,但它不起作用。

public class ServiceCard {
    private static int cardID;

    public ServiceCard() {
        setCardID(getCardID() + 1);
    }   

    public static int getCardID() {
        return cardID;
    }

    public static void setCardID(int cardID) {
        ServiceCard.cardID = cardID;
    }
}

当我进行测试时:

ServiceCard card = new ServiceCard();
System.out.println(card.getCardID());

ServiceCard card2= new ServiceCard();
System.out.println(card2.getCardID());

System.out.println(card.getCardID());

控制台:

1
2
2

1 个答案:

答案 0 :(得分:4)

使 cardID static本身不起作用。因为那样,你的所有实例在任何特定时刻都会有相同的 cardID

您的班级中需要另外一个static字段,该字段将用于将增量值分配给id。此外,在多线程应用程序中,您可以使用AtomicInteger代替,更适合作为原子计数器:

import java.util.concurrent.atomic.AtomicInteger;

public class ServiceCard {

    private int cardID;
    private static AtomicInteger counter = new AtomicInteger(0);

    public ServiceCard() {
        cardID = counter.incrementAndGet();
    }
}

ServiceCard card1 = new ServiceCard();
ServiceCard card2 = new ServiceCard();

System.out.println(card1.getCardID());  // 1
System.out.println(card2.getCardID());  // 2