ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
class A {
void f() { System.out.print("Af "); g(); }
void g() { System.out.print("Ag "); }
}
class B extends A {
void f() { System.out.print("Bf "); super.f(); }
void g() { System.out.print("Bg "); }
}
// in main:
new B().f();- A. Bf Af Bg
- B. Bf Af Ag
- C. Af Bg
- D. Bf Bg
Correct answer: A. Bf Af Bg
super.f() runs A's body statically, but inside it g() is an ordinary virtual call on the same B object, so B's g runs. This is the template-method pattern.
More OOP with C++ and Java questions
- What is printed? java class Pt { int x; Pt(int x) { this.x = x; } public boolean equals(Object o) { return o instanceof Pt && ((Pt) o).x…
- What is printed? java interface Greeter { String name(); default String greet() { return "Hi " + name(); } } class G implements Greeter {…
- Which line fails to compile? java abstract class Shape { abstract double area(); } // in main: Shape a = new Shape(); // L1 Shape b = new…
- Which lines fail to compile? java class P { void f() { } static void g() { } } class C extends P { static void f() { } // L1 void g() { }…
- Which line fails to compile? java class P { Number get() { return 1; } int size() { return 0; } } class C extends P { Integer get() {…
- What is printed? java class T { int n; { n += 5; } T() { this(1); n = 2; } T(int k) { n += k; } } // in main: System.out.print(new T().n);