Java Reference
In-Depth Information
Calling buildBox with 1 point (10,10), width 50 and height 50:
Box: <10, 10, 60, 60>
You can define as many versions of a method as you need to implement the behavior
needed for that class.
When you have several methods that do similar things, using one method to call another
is a shortcut technique to consider. For example, the buildBox() method in lines 17-23
can be replaced with the following, much shorter method:
Box buildBox(Point topLeft, Point bottomRight) {
return buildBox(topLeft.x, topLeft.y,
bottomRight.x, bottomRight.y);
}
The return statement in this method calls the buildBox() method in lines 9-15 with
four integer arguments, producing the same result in fewer statements.
Constructor Methods
You also can define constructor methods in your class definition that are called automati-
cally when objects of that class are created.
A constructor method is a method called on an object when it is created—in other words,
when it is constructed.
Unlike other methods, a constructor cannot be called directly. Java does three things
when new is used to create an instance of a class:
Allocates memory for the object
n
Initializes that object's instance variables, either to initial values or to a default ( 0
for numbers, null for objects, false for Booleans, or '\0' for characters)
n
Calls the constructor method of the class, which might be one of several methods
n
If a class doesn't have any constructor methods defined, an object still is created when
the new operator is used in conjunction with the class. However, you might have to set its
instance variables or call other methods that the object needs to initialize itself.
By defining constructor methods in your own classes, you can set initial values of
instance variables, call methods based on those variables, call methods on other objects,
and set the initial properties of an object.
 
Search WWH ::




Custom Search