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

?

Regards,
Abhishek
The compiler has to be able to statically tell which method signature its trying to invoke, doSomething(Object) in your example. At runtime, the VM will see that doSomething(Object) has been overridden by your derived class, and invoke the derived instance.

What you are trying to do is something called multi-dispatch. Java does not support this concept at the language level.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
.



Relevant Pages

  • Re: Using overload to implement the equivalent of a switch
    ... public abstract void doSomething(Object anObject); ... public void doSomething{ ... AbstractBase reference = new ResponsibleChild; ... different parameter lists. ...
    (comp.lang.java.programmer)
  • Using overload to implement the equivalent of a switch
    ... simulate a dynamic switch ... public abstract void doSomething(Object anObject); ... public void doSomething{ ... AbstractBase reference = new ResponsibleChild; ...
    (comp.lang.java.programmer)
  • RE: MoveNext() method not covered by unit testing?
    ... public void ItemsConstructorTest() ... coverage. ... Microsoft Online Community Support ... nature are best handled working with a dedicated Microsoft Support Engineer ...
    (microsoft.public.vsnet.enterprise.tools)
  • RE: Delegates/events
    ... public void OnMyEvent ... public class Second ... Microsoft Online Community Support ... where an initial response from the community or a Microsoft Support ...
    (microsoft.public.dotnet.languages.csharp)
  • F2k3 Translation - UML 2 Test Profile Example
    ... although I don't know what assertTrue does or how to handle the throw. ... public void addDifferentMoney() ... Support the Original G95 Project: http://www.g95.org ... Support the GNU GFortran Project: http://gcc.gnu.org/fortran/index.html ...
    (comp.lang.fortran)