Java Reference
In-Depth Information
You also can overload constructor methods, as you can do with regular methods, to cre-
ate an object that has specific properties based on the arguments you give to
new
.
Basic Constructor Methods
Constructors look a lot like regular methods, with three basic differences:
They always have the same name as the class.
n
They don't have a return type.
n
They cannot return a value in the method by using the
return
statement.
n
For example, the following class uses a constructor method to initialize its instance vari-
ables based on arguments for
new
:
class VolcanoRobot {
String status;
int speed;
int power;
VolcanoRobot(String in1, int in2, int in3) {
status = in1;
speed = in2;
power = in3;
}
}
You could create an object of this class with the following statement:
VolcanoRobot vic = new VolcanoRobot(“exploring”, 5, 200);
5
The
status
instance variable would be set to
exploring
,
speed
to
5
, and
power
to
200
.
Calling Another Constructor Method
If you have a constructor method that duplicates some of the behavior of an existing con-
structor method, you can call the first constructor from inside the body of the second
constructor. Java provides a special syntax for doing this. Use the following code to call
a constructor method defined in the current class:
this(
arg1
,
arg2
,
arg3
);
The use of
this
with a constructor method is similar to how
this
can be used to access a
current object's variables. In the preceding statement, the arguments with
this()
are the
arguments for the constructor method.