Shan
Shan

Reputation: 5242

Private Constructor initialized by a public method

I came cross a class with private constructor but the object is returned by another public method by call to the private constructor. What may be the advantage of such a construct when we could have made the constructor public?

public final class TokenTable {

    static public int errorToken = 0; 
    static public int timesToken = 1;
    static public int divToken = 2;
    static public int plusToken = 11;
    ......
    ......

    private final HashMap<String, Integer> keywordMap = new HashMap();
    private final HashMap<String, Integer> operationMap = new HashMap();

    private TokenTable() {

        operationMap.put("*", timesToken);
        operationMap.put("/", divToken);
        operationMap.put("+", plusToken);
        ....



    }


    static public TokenTable getInstance() {

            LexTokenTabInstance = new TokenTable();
            return LexTokenTabInstance;
    }

}

Upvotes: 0

Views: 3618

Answers (5)

Shreyos Adikari
Shreyos Adikari

Reputation: 12754

If you do not want to protect creation of multiple instance outside the class then you can create private constructor.
This is helpful creating a single instance.
You can do it like(Eager loading):

private static final TokenTable tokenTable = new TokenTable();

static public TokenTable getInstance() {

          return tokenTable;
    }

Or, you can do it like(Lazy loading):

private static TokenTable tokenTable;

static public TokenTable getInstance() {
         if(null == tokenTable){
         tokenTable = new TokenTable(); 
         }
          return tokenTable;
    }

Upvotes: 0

John B
John B

Reputation: 32969

This is called the Factory pattern. Check out the description here - Factory Design Pattern.

There are several advantages:

  • you can have multiple named factory methods to create different flavors of the object which can allow for overloading with the same set of parameter types
  • you can return a singleton if appropriate or maybe return one of a cached set of instances
  • if don't need to use new
  • when using generics, the generic type is inferred by the compiler so don't need to use the <> operator
  • you can return an interface instead of a concrete class
  • allows for pre-constructor initialization (for example if init must be done prior to calling base class constructor)

To be clear, the above example it seems that it was done just as a "good practice" since none of the above capabilities was used (other than you don't have to use "new").

Upvotes: 6

JB Nizet
JB Nizet

Reputation: 692181

This is called a factory method. A factory method has many advantages over a constructor:

  • it has a name (and multiple factory methods may have different names)
  • it allows returning a cached instance instead of a new instance
  • it allows returning a subclass instance instead of the actual class
  • etc.

Upvotes: 3

Andrew Martin
Andrew Martin

Reputation: 5761

The primary reason for hiding a constructor of a class is to control how objects of that class are created. A common example of this is in the Singleton pattern, where only one object of a class is instantiated.

In order to police this, the user accesses a static method which will access the private constructor if the object isn't created, or else return a reference to the already created object:

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {       }

    public static SingletonDemo getInstance() {
            if (instance == null) {
                    synchronized (SingletonDemo.class){
                            if (instance == null) {
                                    instance = new SingletonDemo();
                            }
                  }
            }
            return instance;
    }
}  

For other examples, look at Factory patterns in general: http://en.wikipedia.org/wiki/Factory_method_pattern

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19304

The main advantage is that no one can create an instance, but using static getInstance method.

This way you can make sure only one instance is created, just as Singelton design pattern

Upvotes: 0

Related Questions