Where and how can I 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
Updated on: 2020-02-25T10:17:06+05:30

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements