Java Reference
In-Depth Information
PITFALL: You Cannot Overload Based on the Type Returned
If you think about it, there is no way that Java could allow this sort of overloading.
Suppose
anObject
is an object of the class
SampleClass2
. Then in the following
assignment, Java could not decide which of the above two method definitions to use:
double
answer = anObject.computeSomething(10);
Either a value of type
int
or a value of type
double
can legally be assigned to the vari-
able
answer
. So, either method definition could be used. Because of such problems,
Java says it is illegal to have both of these method headings in the same class.
■
You Cannot Overload Operators in Java
Many programming languages, such as C++, allow you to overload operators, such as
+
, so
that the operator can be used with objects of some class you define, as well as being used
for such things as numbers. You cannot do this in Java. If you want to have an “addition” in
your class, you must use a method name, such as
add
, and ordinary method syntax; you
cannot define operators, such as the
+
operator, to work with objects of a class you define.
Self-Test Exercises
20. What is the signature of each of the following method headings?
public void
doSomething(
int
p1,
char
p2,
int
p3)
public void
setMonth(
int
newMonth)
public void
setMonth(String newMonth)
public int
amount(
int
balance,
double
duration)
public double
amount(
int
balance,
double
duration)
21. Consider the class
DateSixthTry
in Display 4.11. Would it be legal to add two
method definitions with the following two method headings to the class
DateSixthTry
?
public void
setMonth(
int
newMonth)
public void
setMonth(String newMonth)
22. Consider the class
DateSixthTry
in Display 4.11. Would it be legal to add two
method definitions with the following two method headings to the class
DateSixthTry
?
public void
setMonth(
int
newMonth)
private void
setMonth(
int
newMonth)