Alex Rivera | Logout

What is the use of making constructor private in a class?

Asked 2010-01-14T06:29:09.413
143

Why should we make the constructor private in class? As we always need the constructor to be public.

oop
Edit
Report

2 Answers

0

Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:

public final class UtilityClass {
    private UtilityClass() {}

    public static utilityMethod1() {
        ...
    }
}
answered 2010-01-14T06:51:56.210
0

You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)

answered 2010-03-05T09:49:26.043

Your Answer