Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java overloaded method

Tags:

java

I have an abstract template method:

class abstract MyTemplate
{
    public void something(Object obj)
    {
        doSomething(obj)

     }

    protected void doSomething(Object obj);

}

class MyImpl extends MyTemplate
{

   protected void doSomething(Object obj)
   {
      System.out.println("i am dealing with generic object");
   }

   protected void doSomething(String str)
   {
      System.out.println("I am dealing with string");
   }
}


public static void main(String[] args)
{
   MyImpl impl = new MyImpl();
   impl.something("abc"); // --> this return "i am dealing with generic object"

}

How can I print "I am dealing with string" w/o using instanceof in doSomething(Object obj)?

Thanks,

like image 405
Sean Nguyen Avatar asked Jan 25 '26 09:01

Sean Nguyen


1 Answers

Well you really can't do it. Java can't do double dispatch out of the box. The problem is that the binding of the method calls is usually done mostly at compile time.

Here http://en.wikipedia.org/wiki/Double_dispatch

and here

http://www.javaperformancetuning.com/articles/ddispatch2.shtml

like image 177
Mihai Toader Avatar answered Jan 27 '26 23:01

Mihai Toader