ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Util {
    static int counter = 0;
    static void inc() { counter++; }
}
class UtilChild extends Util {
}
public class Main {
    public static void main(String[] args) {
        Util.inc();
        UtilChild.inc();
        System.out.println(Util.counter + " " + UtilChild.counter);
    }
}
  1. A. 1 1
  2. B. 1 2
  3. C. 2 2
  4. D. Compile-time error: UtilChild does not declare counter or inc()

Correct answer: C. 2 2

Static members are not duplicated per subclass; UtilChild.counter and UtilChild.inc() are just convenient aliases for the single Util.counter field and Util.inc() method inherited from Util. Both calls to inc() increment the very same shared counter, so both Util.counter and UtilChild.counter report 2.

More OOP with C++ and Java questions

Exams that ask this topic