ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
interface Payable {
    double rate();
    default double monthly(double hours) { return hours * rate(); }
}
class Intern implements Payable {
    public double rate() { return 15.0; }
}
class SeniorIntern extends Intern {
    @Override
    public double rate() { return 25.0; }
}
public class Main {
    public static void main(String[] args) {
        Payable p = new SeniorIntern();
        System.out.println(p.monthly(10));
    }
}
  1. A. 150.0
  2. B. 250.0
  3. C. Compile-time error: SeniorIntern cannot override an interface implementation inherited from a class
  4. D. 0.0

Correct answer: B. 250.0

monthly() is a default method inherited by Intern (and transitively by SeniorIntern) from Payable; it calls rate() polymorphically. Since p's runtime type is SeniorIntern, rate() dispatches to SeniorIntern's override, returning 25.0, so monthly(10) computes 10 * 25.0 = 250.0.

More OOP with C++ and Java questions

Exams that ask this topic