我有带有字段的 ServiceCard 类private int cardID
,当我创建一个或多个 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