Static Variables and Methods

AP Computer Science A· difficulty 4/5

public class Counter {
    private int count;
    public static void inc() {
        count++;
    }
}

What is wrong?

  • A

    Nothing is wrong

  • B

    count must be public

  • C

    inc must return int

  • D

    Static methods cannot access instance field count without an object reference

    check_circle

Explanation

Static methods belong to the class; they cannot reference instance fields directly. Either make count static or make inc an instance method.

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

Related questions