
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Private Constructor in Java
We can use a private contractor in a Java while creating a singleton class. The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.
Example
The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance –
public class SingletonSample { private static SingletonSample singleton = new SingletonSample(); private SingletonSample() { } public static SingletonSample getInstance() { return singleton; } protected static void demoMethod( ) { System.out.println("demoMethod for singleton"); } public static void main(String[] args) { SingletonSample tmp = SingletonSample.getInstance( ); tmp.demoMethod( ); } }
Output
demoMethod for singleton
Advertisements