Java Reference
In-Depth Information
Tip
the name of a constructor must match the simple name, not the fully qualified name, of the class.
Unlike a method, a constructor does not have a return type. You cannot even specify void as a return type for a
constructor. Consider the following declaration of a class Test2 :
public class Test2 {
// Below is a method, not a constructor.
public void Test2() {
// Code goes here
}
}
Does the class Test2 declare a constructor? The answer is no. The class Test2 does not declare a constructor.
Rather, what you may be looking at is a method declaration, which has the same name as the simple name of the class.
It is a method declaration because it specifies a return type of void . Note that a method name could also be the same
as the class name as shown above.
Just the name itself does not make a method or constructor. If the name of a construct is the same as the simple
name of the class, it could be a method or a constructor. If it specifies a return type, it is a method. If it does not specify
a return type, it is a constructor.
When do you use a constructor? You use a constructor with the new operator to initialize an instance (or an
object) of a class just after the new instance is created. Sometimes the phrases “create” and “initialize” are used
interchangeably in the context of a constructor. However, you need to be clear about the difference in creating and
initializing an object. The new operator creates an object and a constructor initializes the object.
The following statement uses a constructor of the Test class to initialize an object of the Test class:
Test t = new Test();
Figure 6-22 shows the anatomy of the above statement. The new operator is followed by the call to the constructor.
The new operator along with the constructor call, for example "new Test()" , is called an instance (or object) creation
expression. An instance creation expression creates an object in memory, executes the code in the body of the
specified constructor, and finally, returns the reference of the new object.
Returns reference of the
newly created object
Test t = new Test( ) ;
A call to constructor
The new operator
Figure 6-22. Anatomy of a constructor call with the new operator
I have covered enough theories for declaring a constructor. It is time to see a constructor in action. Listing 6-26
has the code for a Cat class.
 
Search WWH ::




Custom Search