ProgrammingHardProduct-company placement · GATE CS
Joshua Bloch recommends implementing a singleton as a single-element enum. Which advantage does this give over a class with a private constructor and a static final INSTANCE field?
- A. Serialisation and reflection cannot create a second instance, because the JVM forbids constructing enum constants and deserialises them by name
- B. Enums are created lazily on first use, so startup is faster
- C. An enum singleton can be subclassed for testing
- D. Enum methods are automatically synchronised
Correct answer: A. Serialisation and reflection cannot create a second instance, because the JVM forbids constructing enum constants and deserialises them by name
A normal singleton can be duplicated by deserialisation (unless readResolve is written) or by reflectively calling the private constructor. The JVM guarantees each enum constant is unique, so both attacks fail. Enum methods are not automatically synchronised.
More OOP with C++ and Java questions
- What is printed? cpp struct P { const char s; P(const char s) : s(s) { cout << s; } ~P() { cout << "~" << s; } }; struct B { P b{"B"}; }…
- What is printed? cpp struct B { virtual ~B() { hi(); } virtual void hi() { cout << "B"; } }; struct D : B { ~D() { hi(); } void hi()…
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { using B::f; void…
- What is printed? cpp struct B { virtual char id() const { return 'B'; } }; struct D : B { char id() const override { return 'D'; } }; void…