ProgrammingHardIBM · Deloitte pattern
What happens when this is compiled?
What happens when this is compiled?
enum Operation {
ADD { public int apply(int a, int b) { return a + b; } },
MULTIPLY { public int apply(int a, int b) { return a * b; } };
public abstract int apply(int a, int b);
}
public class Main {
public static void main(String[] args) {
System.out.println(Operation.ADD.apply(2, 3) + " " + Operation.MULTIPLY.apply(2, 3));
}
}- A. Compile-time error: enum constants cannot have bodies
- B. 5 6
- C. Compile-time error: abstract methods are not allowed in enums
- D. 6 5
Correct answer: B. 5 6
Java enums may declare an abstract method and let each constant supply its own body (a constant-specific class body), effectively creating an anonymous subclass per constant. ADD.apply(2,3) runs its own body, 2+3=5; MULTIPLY.apply(2,3) runs its own, 2*3=6.
More OOP with C++ and Java questions
- What is printed? cpp struct Logger { Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger() { cout << "Ctor…
- What is printed? java class Base { Base() { System.out.print("Base "); } } abstract class Middle extends Base { Middle() {…
- What is printed? cpp class Matrix { public: Matrix operator(const Matrix &o) const { cout << "mul "; return Matrix(); } Matrix…
- What is printed? java class Base { public Base() { System.out.print("Base() "); } } class Sub extends Base { public Sub() { super()…
- What is printed? cpp struct Shape { virtual ~Shape() = default; virtual double area() const { return 0; } }; struct Circle : Shape {…
- What is printed? java class Counter { private int count; public synchronized void inc() { count++; } public int get() { return count; } }…