-1

I have class ServiceCard with the field private int cardID, and when I make one or more instances of ServiceCard, I want the first instance have cardID=1, the second instance have cardID=2, etc.

I try to make cardID to static, but it didn't work.

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;
    }
}

When I make a test :

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

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

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

Console:

1
2
2
Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50
Svetoslav Angelov
  • 667
  • 1
  • 6
  • 10

1 Answers1

4

Making the cardID static itself won't work. Because then, all your instances would have the same cardID at any given moment.

You need to have another static field in your class, which will be used to assign incremental values to id. Also, you can use an AtomicInteger instead, which is better suited as atomic counter, in case of multithreaded application:

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
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525