|
You can control the object creation process by applying access modifiers to constructors. For instance, let us see the effect of private modifier on constructors. When you apply a private modifier to a class constructor, it becomes inaccessible from outside the class. If all the constructors of a class are made private, it would be impossible (from outside the class) to instantiate such class. Though this seems to be a disadvantage, it has been proved to be a useful technique, especially if you want-
to restrict the object creation process for your class.
to restrain the number of instances that can be created
from the class.
For example, consider a scenario where there are multiple Java applications running. It is likely that all the Java applications run in the same runtime environment. The class representing the environment, like the class java.lang.Runtime should therefore have only single instance. However, how will you ensure that there is only one instance for the given class? This problem is well known and solved by the singleton design pattern.
|
|
Design Patterns are solutions to the recurrent design problems. Singleton is one such pattern. It provides solution to the design problem where a class wants to allow only one instance to be created. |
In singleton pattern, a class is made responsible for keeping the track of its sole instance. The class must also ensure that no other instance can be created and it should provide a way to access the sole instance. Listing 3.20 demonstrates how a private constructor is used to ensure a single instance for class Singleton. The class also provides a static method getInstance() for accessing that instance (from outside the class).

To restrain instance creation, all constructors must be declared as private. Then no other class can create an instance of such class. Note that the constructor must be explicitly made private and there must be at least one such constructor. Otherwise, the compiler creates a default constructor (we will soon discuss it in next section 3.9), which is accessible, and thus allowing instance creation. The method for accessing instance (the getInstance() method in our example) is made static for two reasons. First, this method is accessing a static variable. Therefore, it has to be static. Secondly, it must be accessible without any need of instantiating the singleton class
|
|
Singleton pattern is not part of SCJP objectives but it is a good example of when you will need to declare the constructors as private. |