Re: Using overload to implement the equivalent of a switch
- From: Daniel Pitts <newsgroup.spamfilter@xxxxxxxxxxxxxxxxxxx>
- Date: Wed, 13 Aug 2008 12:20:24 -0700
Everyone wrote:
Hello!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.
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
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/>
.
- References:
- Using overload to implement the equivalent of a switch
- From: Everyone
- Using overload to implement the equivalent of a switch
- Prev by Date: Re: Can Not find bean in scope error when trying to display in jsp
- Next by Date: Re: JDK implementation of inner classes doesn't match Java Language Specification
- Previous by thread: Re: Using overload to implement the equivalent of a switch
- Next by thread: Exit Value = 35584 from Java.lang.Process
- Index(es):
Relevant Pages
|