ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Shape {
double scale = 1.0;
double area() { return 0; }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override
double area() { return Math.PI * r * r * scale; }
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle(2);
c.scale = 2.0;
Shape s = c;
System.out.printf("%.2f", s.area());
}
}- A. 12.57
- B. 25.13
- C. 6.28
- D. Compile-time error: scale is not visible through a Shape reference's area()
Correct answer: B. 25.13
scale is a regular inherited field, shared between the Shape view and the Circle object (there's only one scale value per object, not per reference type). Setting c.scale = 2.0 mutates the actual object; s.area() dispatches to Circle's override, which reads that same scale, computing pi*2*2*2.0 ≈ 25.13.
More OOP with C++ and Java questions
- What is printed? java class Base { protected int code() { return 1; } } class Mid extends Base { @Override protected int code() { return…
- What is printed? cpp struct Logger { static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int Logger::instances =…
- What is printed? java interface Taxed { default double afterTax(double amt) { return amt 0.9; } } class Product implements Taxed { double…
- What is printed? cpp struct A { virtual std::string name() const { return "A"; } }; struct B : A { std::string name() const override {…
- What is printed? cpp struct Member { Member() { std::cout << "Member "; } ~Member() { std::cout << "~Member "; } }; struct Base { Base() {…
- What is printed? cpp struct A { A() { std::cout << "A "; } }; struct B { B() { std::cout << "B "; } }; struct C : A, B { C() { std::cout…