Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java singleton class vs final class

Can somebody, please explain me clearly on java singleton design pattern class vs java final class.

Can we use a final class instead of using a singleton class?

For a final class we can create the instance of the class and use the methods in that, but not overriding properties, if the methods are static in the final class, then we can just call the methods like ClassName.getMethod, why should we go for singleton instead of final class?

like image 651
Raju Sidda Avatar asked Dec 19 '22 11:12

Raju Sidda


2 Answers

A final class is one which cannot be extended. You can have any number of instances in a final class. The best example of a final class is String. Singleton is a single instance of a class. So both are not exactly same, however you can make your singleton class final to restrict someone from extending it.

like image 139
Raghav Avatar answered Jan 01 '23 13:01

Raghav


You can't extend a final class and there is only single instance for a singleton class. So inheritance concept is not applicable for the final class. But you can create any number of instances in final class but you can't in Singleton.

i.e, final class is immutable class, can create more than one instance but where as Singleton class has only single instance.

like image 43
Shailendra Madda Avatar answered Jan 01 '23 13:01

Shailendra Madda