Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^348) | Inheritance, Polymorphism, and Scope
and an int. Java decides which version to call based on the arguments in the statement that
invokes JTextField.
The following method headings have different signatures and thus overload each other:
public static voidsomeName(int formal1, int formal2, int formal3)
public static voidsomeName(int formal1, doubleformal2, int formal3)
public static voidsomeName(doubleformal1, int formal2, int formal3)
public static voidsomeName(int formal1, int formal2, String formal3)
Even though all of these parameters have the same names, the differences in their types en-
able Java to distinguish among them. For example, the statement
someName(1, 2.0, 3);
calls the second version because it has an intvalue, a doublevalue, and another intvalue as
its arguments. If we write the call as
someName(1.0, 2, 3);
then the double,int,intpattern of its arguments identifies the third version of the method
as the target of the call.
The following method headings all have the same signature and cannot be declared to-
gether in a class. Their signature is the method name (aName) and the presence of three pa-
rameters of types int,double, and String, in that order.
public static voidaName(int formal1, doubleformal2, String formal3)
public static voidaName(int large, doublemedium, String small)
public voidaName(int red, doublegreen, String blue)
static intaName(int thing1, doublething2, String hatCat)
Keep in mind that the types of the parameters determine the signature of a method. The
names of the parameters, the return type, and the modifiers of a method are not part of its
signature.
Overloading is related to, but different from, hiding and overriding. Hiding and overrid-
ing are mechanisms whereby a name is replaced when the same name is declared in a new
context. For example, an instance method identifier overrides a method with the same name
in its superclass if it has the same signature. The declaration in the derived class results in
an identifier that duplicates the one in the superclass. Because they are in different classes,
however, the duplication is acceptable. When we use the identifiers, we indicate which one
we mean. An instance identifier is associated with a specific object of one or the other class
type, and a class identifier is preceded with the name of the class and a period.
If we declare a method with the same name as an inherited superclass method, but the
methods have different signatures, then the new method overloads the name of the super-
class method. The two identifiers are the same, but the different signatures allow them to
be distinguished. Different signatures also serve to distinguish overloaded methods within
the same class. The Java compiler decides which version to call by comparing the types of
the arguments with the types of the parameters in each signature.

Free download pdf