ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
// file a/P.java
package a;
public class P {
    void f() { System.out.print("P"); }      // package-private
    public void call() { f(); }
}
// file b/C.java
package b;
public class C extends a.P {
    void f() { System.out.print("C"); }
}
// in main:
new b.C().call();
  1. A. C
  2. B. Compile-time error: f() in C cannot override f() in P
  3. C. PC
  4. D. P

Correct answer: D. P

A package-private method is not visible outside package a, so C.f does not override P.f; it is an unrelated new method. call() therefore invokes P's own f.

More OOP with C++ and Java questions

Exams that ask this topic