ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
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);
}
// in main:
Operation op = Operation.valueOf("MULTIPLY");
System.out.println(op.apply(3, 4) + " " + op.ordinal() + " " + op.name());- A. 12 1 MULTIPLY
- B. 7 1 MULTIPLY
- C. 12 0 MULTIPLY
- D. 7 0 ADD
Correct answer: A. 12 1 MULTIPLY
valueOf("MULTIPLY") resolves to the MULTIPLY constant, whose apply dispatches to its own override: 3*4=12. ordinal() returns its declaration-order position (MULTIPLY is the second constant, index 1). name() returns the exact declared constant name, "MULTIPLY".
More OOP with C++ and Java questions
- What is printed? cpp class Shape { public: Shape& operator=(const Shape&) = delete; Shape() = default; }; int main() { Shape a, b; a = b; }
- What is printed? java class Parent { protected int score = 50; int getScore() { return score; } } class Child extends Parent { Child() {…
- What is printed? java class Base { void greet() { System.out.print("Base "); helper(); } private void helper() {…
- What is printed? cpp struct Base { virtual void save() { cout << "BaseSave "; } }; struct Derived : Base { void save() override { cout <<…
- What is printed? java class Animal { String sound() { return "..."; } } class Dog extends Animal { @Override String sound() { return…
- What is printed? cpp struct Base { virtual int value() const { return 10; } }; struct Derived : Base { int value() const override { return…