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);
}
}- A. 1 1
- B. 1 2
- C. 2 2
- 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
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…
- What is printed? cpp struct Counter { static int next() { static int n = 0; return ++n; } }; int main() { cout << Counter::next() <<…
- What is printed? cpp class Account { double balance; public: Account(double b) : balance(b) {} Account operator+(const Account &other)…
- What is printed? java class Base { public static void greet() { System.out.print("Base.greet "); } } class Sub extends Base { public…
- What is printed? cpp struct Base { void greet() { cout << "Base::greet "; } }; struct Sub : Base { void greet() { cout << "Sub::greet "; }…