ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
interface Taxed { default double afterTax(double amt) { return amt * 0.9; } }
class Product implements Taxed {
    double price;
    Product(double p) { price = p; }
}
class LuxuryProduct extends Product implements Taxed {
    LuxuryProduct(double p) { super(p); }
    @Override
    public double afterTax(double amt) { return amt * 0.7; }
}
public class Main {
    public static void main(String[] args) {
        Taxed t = new LuxuryProduct(100);
        System.out.println(t.afterTax(100));
    }
}
  1. A. 90.0
  2. B. 70.0
  3. C. Compile-time error: LuxuryProduct cannot re-implement Taxed, which Product already implements
  4. D. 100.0

Correct answer: B. 70.0

Re-declaring implements Taxed in a subclass that already inherits it transitively is redundant but legal in Java (no error). LuxuryProduct overrides afterTax(), and t's runtime type is LuxuryProduct, so t.afterTax(100) dispatches to the override, returning 100*0.7=70.0.

More OOP with C++ and Java questions

Exams that ask this topic