Tutorial :constructors in java [duplicate]



Question:

Possible Duplicates:
Why do we need a private constructor?
Can a constructor in Java be private?

whts the use of private constructor in java?


Solution:1

One more thing you can achive is SingleTon pattern with the help of the private constructor.

Some thing like this:

public class ClassicSingleton {     private static ClassicSingleton instance = null;     private ClassicSingleton() {        // Exists only to defeat instantiation.     }     public static ClassicSingleton getInstance() {        if(instance == null) {           instance = new ClassicSingleton();        }        return instance;     }  }  


Solution:2

A private constructor allows the developer of a class to better control how this class can be instantiated, e.g. not at all (for a utility class), only internally (for a singleton) or only through factory methods.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »