ProgrammingHardProduct-company placement · GATE CS

What is printed?

What is printed?
class P { String n = "P"; String get() { return n; } }
class C extends P {
    String n = "C";
    String get() { return n; }
    String sup() { return super.n; }
}
// in main:
P p = new C();
System.out.print(p.n + p.get() + ((C) p).n + ((C) p).sup());
  1. A. CCCP
  2. B. PCCP
  3. C. PPCP
  4. D. CCCC

Correct answer: B. PCCP

Fields are not polymorphic: p.n uses the static type P, giving P, while the cast gives C's field. Methods are: p.get() runs C.get(), which reads C's n. super.n in C reads the hidden field P.

More OOP with C++ and Java questions

Exams that ask this topic