Java Reference
In-Depth Information
public static T2 getInstance() {
return T2.instance;
}
/* Other code goes here */
}
You can use the
T2.getInstance()
method to get the reference of an object of the
T2
class.
Internally, the
T2
class does not create a new object every time you call the
T2.getInstance()
method. Rather, it returns the same object reference for all calls to this method.
T2 t1 = T2.getInstance();
T2 t2 = T2.getInstance();
•
Sometimes you want a class to have only static members. It may not make sense to create an
object of such a class. For example, the
java.lang.Math
class declares its constructor
private
.
The
Math
class contains static variables and static methods to perform numeric operations. It
does not make sense to create an object of the
Math
class.
You can also declare all constructors of a class
•
private
to prevent inheritance. Inheritance
lets you define a class by extending the definition of another class. If you do not want anyone
else to extend your class, one way to achieve this is to declare all constructors of your class
private
. Another way to prevent your class from being extended is to declare it
final
. I will
discuss inheritance in detail in the chapter on inheritance.
Let's consider the class
T3
whose constructor has
protected
access level as shown:
// T3.java
package com.jdojo.cls.p1;
public class T3 {
protected T3() {
}
}
A constructor with
protected
access level can be used anywhere in the same package or inside a descendant
class in any package. The class
T3
is in the
com.jdojo.cls.p1
package. You can write the following statement
anywhere in
com.jdojo.cls.p1
package, which creates an object of the
T3
class:
// Valid anywhere in the com.jdojo.cls.p1 package
new T3();
I will cover inheritance in detail later. However, to complete the discussion of a
protected
constructor, you will
use inheritance in the example below. Things about inheritance will be clearer when I discuss it in the chapter on
inheritance. You inherit (or extend) a class using the keyword
extends
. The following code creates a
T3Child
class by
inheriting it from the
T3
class:
// T3Child.java
package com.jdojo.cls.p2;
import com.jdojo.cls.p1.T3;