What is singleton class and how can we make a class singleton?



What is singleton class and how can we make a class singleton?..

Answer / Km Srishti Tripathi

A Singleton class is a design pattern that ensures a class has only one instance, while providing a global point of access to it. In Java, we can achieve singleton behavior using various methods such as the Hungry, Eager, and Lazy Initialization patterns. Here's an example of the Eager Initialization pattern:
```java
public class SingletonExample {
private static final SingletonExample instance = new SingletonExample();

private SingletonExample() {}

public static SingletonExample getInstance() {
return instance;
}
}
```
In the example above, the instance is created when the class is loaded rather than being created on demand. This ensures that only one instance of the `SingletonExample` exists and provides a global access point to it through the `getInstance()` method.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

What are the advantages of unicode?

1 Answers  


Can we clone singleton object?

1 Answers  


What do you mean by object?

1 Answers  


Is empty in java?

1 Answers  


what is the difference b/w design pattern and architecture

4 Answers   Covansys,


Explain differences between checked and unchecked exceptions in java?

1 Answers  


What are different types of classloaders?

1 Answers  


What are the library functions in java?

1 Answers  


What is prefix of a string?

1 Answers  


Difference between this() and super() in java ?

1 Answers  


What defines function?

1 Answers  


How do you sort data in java?

1 Answers  


Categories