ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class EventBus {
private static EventBus instance;
private EventBus() { System.out.print("created "); }
public static EventBus getInstance() {
if (instance == null) instance = new EventBus();
return instance;
}
}
// in main:
EventBus.getInstance();
EventBus.getInstance();
EventBus.getInstance();- A. created
- B. created created created
- C. Compilation error: constructor is private
- D. It throws an exception on the second call
Correct answer: A. created
This is the classic (non-thread-safe but simple) lazy singleton pattern: instance is created only the first time getInstance() finds it null, printing "created" once; subsequent calls just return the already-created instance without constructing again.
More OOP with C++ and Java questions
- What is printed? java class Base { Base clone2() { return new Base(); } } class Derived extends Base { @Override Derived clone2() { return…
- What is printed? java class Animal { void makeSound() { System.out.print("..."); } } class Dog extends Animal { @Override void makeSound()…
- What is printed? java class Base { Base() { System.out.print("Base "); } } class Mid extends Base { Mid() { System.out.print("Mid "); } }…
- What is printed? cpp struct Base { virtual void render() const { cout << "Base::render "; } }; struct Derived : Base { void render() const…
- What is printed? java class Shape { double scale = 1.0; double area() { return 0; } } class Circle extends Shape { double r; Circle(double…
- What is printed? java class Base { protected int code() { return 1; } } class Mid extends Base { @Override protected int code() { return…