Java Reference
In-Depth Information
You can combine the above two statements into one in the code in any package.
// Code inside any package
T1 t = new T1();
Let's consider the following code for the class
T2
, which has a
public
access level and has a constructor with a
private
access level:
// T2.java
package com.jdojo.cls.p1;
public class T2 {
private T2() {
}
}
Because class
T2
has a
public
access level, you can use its name to declare a reference variable in any package.
The constructor for class
T2
has a
private
access level. The implication of having a
private
constructor is that you
cannot create an object of the
T2
class outside the
T2
class. Recall that a
private
method, field, or a constructor
cannot be used outside the class in which it is declared. Therefore, the following code will not compile unless it
appears inside the
T2
class:
// Code outside the T2 class
new T2(); // A compile-time error
What is the use of the
T2
class if you cannot create its object outside of the
T2
class? Here are the possible
situations where you can declare a constructor
private
, and still create and use objects of the class:
•
A constructor is used to create an object of a class. You may want to restrict the number of
objects for a class. The only way you can restrict the number of objects of a class is by having
the full control of its constructors. If you declare all constructors of a class to have the
private
access level, you have full control over how the objects of that class will be created. Typically,
you include one or more
public static
methods in that class, which create and/or return
an object of that class. If you design a class so that only one object of the class may exist,
it is called a singleton pattern. The following code is a version of the
T2
class that is based
on the singleton pattern. It declares a
private static
reference variable called
instance
,
which holds the reference of the
T2
class object. Note that the
T2
class uses its own
private
constructor to create an object. Its
public static getInstance()
method returns the lone
object of the class. More than one object of the
T2
class cannot exist.
// T2.java
package com.jdojo.cls.p1;
public class T2 {
private static T2 instance = new T2();
private T2() {
}