ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
abstract class Shape {
abstract double area();
String describe() { return "Area=" + area(); }
}
class Square extends Shape {
double side;
Square(double s) { side = s; }
double area() { return side * side; }
}
// in main:
Shape s = new Square(4);
System.out.println(s.describe());- A. Compile-time error: Shape cannot call an abstract method from describe()
- B. Area=0.0
- C. Area=16.0
- D. Compile-time error: Shape cannot be used as a reference type since it is abstract
Correct answer: C. Area=16.0
describe() is a concrete method in the abstract class and may freely call the abstract method area(); it is resolved dynamically against the actual object, a Square, whose area() returns 4*4 = 16.0. A reference variable of an abstract type is completely legal, only instantiation of the abstract type itself is forbidden.
More OOP with C++ and Java questions
- What is printed? java class Base { protected String name() { return "Base"; } public String greet() { return "Hi " + name(); } } class…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { virtual void f() { cout << "B"; } }; struct C : B {…
- What is printed? java interface Flyer { default String move() { return "fly"; } } interface Swimmer { default String move() { return…
- What is printed? java class Counter { protected int count = 0; void inc() { count++; } } class LoggingCounter extends Counter { @Override…
- What is printed? cpp struct Base { virtual void f() const { cout << "Base-const"; } }; struct Derived : Base { void f() const override {…
- What is printed? java class Shape { double area() { return 0; } } class Circle extends Shape { double radius; Circle(double r) { radius =…