Static Variables and Methods

AP Computer Science A· difficulty 3/5

public class Item {
    private static int next = 1;
    private int id;
    public Item() { id = next; next++; }
    public int getId() { return id; }
}
// ...
Item a = new Item();
Item b = new Item();
Item c = new Item();
System.out.println(c.getId());

What is printed?

  • A

    3

    check_circle
  • B

    1

  • C

    2

  • D

    0

Explanation

next starts at 1; each constructor assigns the current value to id and increments next, so a=1, b=2, c=3.

Want 10 more like this — adaptive to your weak spots?

Related questions