ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
@Override
double area() { return Math.PI * radius * radius; }
}
// in main:
Shape[] shapes = { new Shape(), new Circle(2) };
double total = 0;
for (Shape s : shapes) total += s.area();
System.out.printf("%.2f", total);- A. 0.00
- B. 12.57
- C. Compile-time error: Shape[] cannot hold a Circle
- D. 4.00
Correct answer: B. 12.57
An array of the base type can freely hold subtype objects. The plain Shape contributes area() = 0; the Circle's overridden area() runs polymorphically, contributing pi*2*2 ≈ 12.566..., so the total prints as 12.57.
More OOP with C++ and Java questions
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } @Override public String toString() { return "N(" + val +…
- What is printed? java class Employee { double bonus() { return 1000; } double pay() { return 50000 + bonus(); } } class Manager extends…
- What is printed? cpp struct Base { Base() { cout << "CtorBase "; } virtual ~Base() { cout << "DtorBase "; } }; struct Derived : Base {…
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…