Java Reference
In-Depth Information
Constructors
A constructor is a named block of code that is used to initialize an object of a class immediately after the object is
created. The structure of a constructor looks similar to a method. However, the similarity between the two stops right
there, in their looks. They are two different constructs and they are used for different purposes.
Declaring a Constructor
The general syntax for a constructor declaration is
<<Modifiers>> <<Constructor Name>>(<<parameters list>>) throws <<Exceptions list>> {
// Body of constructor goes here
}
The declaration of a constructor starts with modifiers. A constructor can have its access modifier as public ,
private , protected , or package-level (no modifier). The constructor name is the same as the simple name of the
class. The constructor name is followed by a pair of opening and closing parentheses, which may include parameters.
Optionally, the closing parenthesis may be followed by the keyword throws , which in turn is followed by a comma-
separated list of exceptions. I will discuss the use of the keyword throws in chapter 9. The body of the constructor
where you place your code is enclosed in braces.
If you compare the syntax to declare a method with the syntax to declare a constructor, you will find that they are
almost the same. It is suggested to keep the method declaration in mind when learning about constructor declaration
because most of the things are similar.
The following code shows an example of declaring a constructor for a class Test . Figure 6-21 shows the anatomy
of the constructor.
Name of the class and name of
constructor must match
public class Test {
Access level
modifier for the
constructor
Body of the
constructor goes
within braces
public Test( ) {
// Code goes here
}
}
Figure 6-21. Anatomy of the constructor for the Test class
// Test.java
package com.jdojo.cls;
public class Test {
public Test() {
// Code goes here
}
}
 
Search WWH ::




Custom Search