ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Shape {
double area() { return 0; }
@Override
public String toString() { return getClass().getSimpleName() + "(area=" + area() + ")"; }
}
class Square extends Shape {
double side;
Square(double s) { side = s; }
@Override
double area() { return side * side; }
}
// in main:
Shape s = new Square(3);
System.out.println(s);- A. Square(area=9.0)
- B. Shape(area=9.0)
- C. Square(area=0.0)
- D. Shape(area=0.0)
Correct answer: A. Square(area=9.0)
getClass() always returns the object's actual runtime class regardless of the static reference type, so getClass().getSimpleName() gives "Square"; area() dispatches virtually to Square's override (3*3=9.0), giving "Square(area=9.0)".
More OOP with C++ and Java questions
- What is printed? cpp class Base { public: Base() { cout << "Base "; } Base& operator=(const Base&) { cout << "Base= "; return this; } }…
- What is printed? cpp struct Base { Base() { cout << "B "; } virtual ~Base() { cout << "~B "; } }; struct Derived : Base { int data…
- What is printed? java class Converter<T, R> { R convert(T input, java.util.function.Function<T, R> fn) { return fn.apply(input); } } // in…
- What is printed? cpp template<typename T> T maxVal(T a, T b) { return a > b ? a : b; } class Money { int cents; public: Money(int c)…
- What is printed? cpp class Shape { public: virtual void draw() const = 0; }; class Group : public Shape { vector<Shape> children; public…
- What is printed? java class Base { public int hashCode() { return 1; } } class Derived extends Base { @Override public int hashCode() {…