Constructors

AP Computer Science A· difficulty 2/5

public class Counter {
    private int count;
    public Counter() { count = 0; }
    public void inc() { count++; }
    public int getCount() { return count; }
}
// ...
Counter c = new Counter();
c.inc(); c.inc(); c.inc();
System.out.println(c.getCount());

What is printed?

  • A

    3

    check_circle
  • B

    0

  • C

    1

  • D

    Compile-time error

Explanation

The default constructor sets count to 0; inc() is called three times, so count becomes 3.

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

Related questions