Static Variables and Methods

AP Computer Science A· difficulty 3/5

public class Widget {
    private static int count = 0;
    public Widget() { count++; }
    public static int getCount() { return count; }
}
// ...
new Widget();
new Widget();
new Widget();
System.out.println(Widget.getCount());

What is printed?

  • A

    3

    check_circle
  • B

    1

  • C

    0

  • D

    Compile-time error

Explanation

The static variable count is shared among all instances; each constructor call increments it, so after three instances count is 3.

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

Related questions