ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
interface Shape {
double area();
default String describe() { return "Shape with area " + area(); }
}
class Square implements Shape {
double side;
Square(double s) { side = s; }
public double area() { return side * side; }
}
// in main:
Shape s = new Square(4);
System.out.println(s.describe());- A. Shape with area 4.0
- B. Shape with area 16.0
- C. Compilation error: describe() calls an abstract method
- D. null
Correct answer: B. Shape with area 16.0
An interface default method can freely call the interface's own abstract methods; at run time, that call (area()) dispatches virtually to the implementing class's method, Square.area() = 4*4 = 16.0, so describe() returns "Shape with area 16.0".
More OOP with C++ and Java questions
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…
- What is printed? cpp struct Counter { static int next() { static int n = 0; return ++n; } }; int main() { cout << Counter::next() <<…
- What is printed? cpp class Account { double balance; public: Account(double b) : balance(b) {} Account operator+(const Account &other)…