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));
}
}- A. 150.0
- B. 250.0
- C. Compile-time error: SeniorIntern cannot override an interface implementation inherited from a class
- 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
- What is printed? cpp struct Base { virtual void print() const { cout << "Base"; } friend ostream& operator<<(ostream &os, const Base &b) {…
- What is printed? java class Shape { public boolean equals(Object o) { return o instanceof Shape; } public int hashCode() { return 1; } }…
- What is printed? java class Base { static int shared = 0; int id; Base() { id = ++shared; } } class Sub extends Base { } public class Main…
- What is printed? java class Base { Base(String tag) { System.out.print("Base:" + tag + " "); } } class Sub extends Base { Sub() {…
- What is printed? cpp struct Shape { virtual double area() const = 0; bool operator<(const Shape &o) const { return area() < o.area(); } }…
- What is printed? java class Matrix { int[][] data; Matrix(int n) { data = new int[n][n]; } @Override public boolean equals(Object o) { if…