Java · Question 12 · Hard

What will be the output of the following Java program?

class P {
    static String who() { return "P"; }
    String me() { return "p"; }
}

class C extends P {
    static String who() { return "C"; }
    String me() { return "c"; }
}

public class Main {
    public static void main(String[] args) {
        P obj = new C();
        System.out.println(obj.who() + obj.me());
    }
}
  1. Cc
  2. Pp
  3. Pc
  4. Cp
Answer and explanation

Answer: C. Pc

Explanation: Static methods are not overridden, only hidden, so obj.who() is chosen by the reference type P and returns "P". me() is an instance method, so it is overridden and returns "c".

Previous: What will be the output of the following Java program? · Next: What will be the output of the following Java program (default JVM settings)?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge