Re: Why this overloading example works this way?
Gabriel Belingueres wrote:
I share your opinion in that introducing such a "type inference"
behavior in the compiler would complicate things enough to drive you
mad.
But, I think this is a valid check that the compiler can do without
sacrificing too much the compilation performance, and output a warning
message when it parse code like this, so that the programmer can make
your mind about that he/she want. Something like this:
Ah, but then it wouldn't be Java would it?
When the compiler encounters code like this (where B is a subclass of
A):
final A p2 = new B();
o.method(p2);
AND there exists overloaded methods taking a B instance and some
instance of a superclass of B, then mark the method call as
"suspicious", so that the programmer can take some action:
If he/she really meant having a final B instance, then declare it:
final B p2 = new B();
o.method(p2);
If he/she really meant to have an A instance because he/she will use
the same variable with other dynamic type, then he/she can take out the
final modifier:
A p2 = new B();
o.method(p2);
Gabriel
If he/she really wanted a final A local variable referencing a B
instance, then I think it is OK to SHOW A WARNING, though the class
file compiles normally under the current overloading rules.
First of all, "final" has nothing to do with overloading. A "final" variable
is one that cannot be reassigned.
Most telling, there are times when one wants to declare overloads that differ
only where a parameter in one is of a supertype of that from the other. The
overload with the subtype is called a "specialization", and it is a perfectly
valid idiom.
E.g.,
A is a supertype of B
X declares methods:
public T foo( A parm );
and
public T foo( B parm );
as in
public boolean equals( Object obj )
{
if ( obj instanceof X )
{
return equals( (X) obj );
}
else
{
return false;
}
}
(The return statement would be more compact as:
return (obj instanceof X? equals( (X) obj ) : false);
)
We don't want warnings here. In any case, this is how Java works.
- Lew