Anonymous Class in Java – Definition, Syntax, and Example
![]() |
Singleton Class in Java – Definition, Syntax, and Example
Definition:
A Singleton Class in Java is a design pattern that ensures only one instance of the class exists in the JVM. It provides a global point of access to that instance.
Key Points:
- Only one instance is created during the entire lifecycle.
- Private constructor to prevent external instantiation.
- Static method to provide access to the single instance.
Syntax Example:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Main {
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
System.out.println(obj1 == obj2); // true
}
}
Advantages:
- Controlled access to the single instance.
- Reduces memory footprint.
- Ensures consistent state across application.
Limitations:
- Difficult to test with multiple instances.
- Can introduce global state issues.
❓ Frequently Asked Questions
Q1: Can a Singleton class have parameters in the constructor?
No. Singleton constructors are private and parameters are not allowed for external calls.
Q2: Is Singleton thread-safe by default?
No, you need to implement synchronization for multi-threaded environments.
Q3: Can Singleton be broken by serialization?
Yes, unless you override readResolve()
method.
Comments
Post a Comment