Java Reference
In-Depth Information
In the first call to multiply() in the OverloadDemo program, a and b are
passed in. Because a and b are both ints, the following version of multiply() in
the Calculator class is invoked:
public int multiply(int x, int y)
When the two doubles d1 and d2 are passed in to multiply(), the corre-
sponding overloaded version in Calculator is invoked:
public double multiply(double x, double y)
In the following statement, only a single int is passed in, so the version of
multiply that takes in a single int is invoked:
intAnswer = calc.multiply(b);
Similarly, invoking multiply() with three int arguments causes the corre-
sponding multiply() with three int parameters to be invoked.
I want to make an observation about the following statement in the Over-
loadDemo program:
doubleAnswer = calc.multiply(b, f);
The arguments are of type int and float, in that order. There is no multiply()
method in the Calculator class that has a parameter list with an int and a float.
However, because a float can be promoted to a double, notice that the multi-
ply() method that gets invoked is the following:
public double multiply(int x, double y);
This situation in which the float is passed in to a double arises all the
time when invoking methods (not just when a method is overloaded).
When an argument does not exactly match a parameter, but the argument
can be promoted to match a parameter, then the promotion will occur
automatically.
Constructors
A constructor is a special method in a class that is invoked when the object gets
instantiated. The purpose of a constructor is to allow the fields of the object to
be initialized when the object is instantiated.
Search WWH ::




Custom Search