Java Reference
In-Depth Information
type of arguments, or both. Java allows method overloading as long as each argument list
is unique for the same method name.
CAUTION
Java does not consider the return type when differentiating among
overloaded methods. If you attempt to create two methods with
the same signature and different return types, the class won't
compile. In addition, the variable names that you choose for each
argument to the method are irrelevant. The number and the type
of arguments are the two things that matter.
The next project creates an overloaded method. It begins with a simple class definition
for a class called Box , which defines a rectangular shape with four instance variables to
define the upper-left and lower-right corners of the rectangle, x1 , y1 , x2 , and y2 :
class Box {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
}
When a new instance of the Box class is created, all its instance variables are initialized
to 0 .
A buildBox() instance method sets the variables to their correct values:
Box buildBox(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
5
}
This method takes four integer arguments and returns a reference to the resulting Box
object. Because the arguments have the same names as the instance variables, the key-
word this is used inside the method when referring to the instance variables.
This method can be used to create rectangles, but what if you wanted to define a rectan-
gle's dimensions in a different way? An alternative would be to use Point objects rather
than individual coordinates because Point objects contain both an x and y value as
instance variables.
Search WWH ::




Custom Search