Junior — Middle
What is meant by deferred object initialization in programming and how is it implemented?
sobes.tech AI
Answer from AI
Lazy initialization is a technique where an object or its part is created not at the moment of declaration, but at the first access to it. This helps save resources if the object might not be needed.
In Java, this can be implemented in several ways:
- Using the
lazykeyword is not available, but you can implement it through null checks and initialization upon first call.
Example:
public class MyClass {
private ExpensiveObject obj;
public ExpensiveObject getObj() {
if (obj == null) {
obj = new ExpensiveObject();
}
return obj;
}
}
- Using an inner static class for thread-safe lazy initialization.
Lazy initialization is useful when creating the object is expensive and not always required.