ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
interface Shape {
static double unit() { return 1.0; }
double area();
}
class Square implements Shape {
double side;
Square(double s) { side = s; }
public double area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Square sq = new Square(3);
System.out.println(Shape.unit() + " " + sq.area());
}
}- A. 1.0 9.0
- B. Compile-time error: interfaces cannot have static methods
- C. 1.0 1.0
- D. Compile-time error: sq.unit() must be used instead of Shape.unit()
Correct answer: A. 1.0 9.0
Since Java 8, interfaces may declare static methods, but they belong to the interface itself and must be called as Interface.method(), never inherited or called through an implementing instance. Shape.unit() returns 1.0, and sq.area() (an abstract method Square implements) returns 3*3 = 9.0.
More OOP with C++ and Java questions
- 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)…
- What is printed? java class Base { public static void greet() { System.out.print("Base.greet "); } } class Sub extends Base { public…
- What is printed? cpp struct Base { void greet() { cout << "Base::greet "; } }; struct Sub : Base { void greet() { cout << "Sub::greet "; }…
- What is printed? cpp struct Base { static void hello() { cout << "Base::hello "; } }; struct Derived : Base { static void hello() { cout…
- What is printed? java class Outer { static int x = 100; static class Nested { int x = 200; void show() { System.out.println(x + " " +…