Yes, a constructor can be private in Java.
Possible Scenarios
a. A class with all static methods.
Suppose you define an utility class with all static methods, then there is no point of creating an object to this class. In this scenario, you can create a private constructor, so the object is not created from outside.
package com.smaple.app.utils;
public class ArithmeticUtil {
private ArithmeticUtil(){
}
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
}
b. In Singleton Design Pattern.
Singleton pattern restricts the instantiation of a class to one object. That is you can't create more than one object to this class. This is useful when exactly one object is needed to coordinate actions across the system.
c. To get more control on instantiation of objects
We can use it in Singleton Design pattern, builder design pattern and multiton pattern.
You may
like
No comments:
Post a Comment