ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed?

What is printed?
class P {
    String n = "P";
    static String s() { return "Ps"; }
    String t() { return "Pt"; }
}
class C extends P {
    String n = "C";
    static String s() { return "Cs"; }
    String t() { return "Ct"; }
}
// in main:
P p = new C();
System.out.print(p.n + p.s() + p.t() + ((C) p).n);
  1. A. PPsCtC
  2. B. PPsPtP
  3. C. PCsCtC
  4. D. CCsCtC

Correct answer: A. PPsCtC

Fields and static methods are resolved by the static type (P), only instance methods are virtual: p.n = P, p.s() = Ps, p.t() = Ct; the cast to C selects C's field.

More OOP with C++ and Java questions

Exams that ask this topic