Java overloaded method

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'm dealing with a string” without using an instance in doSomething (Object obj)?

Thank,

+3
source share
4 answers

Well, you really can't do it. Java cannot do double dispatch out of the box. The problem is that method call bindings are usually done mostly at compile time.

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

and here

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

+2
source

Impossible. doSomething (Object obj) in MyImpl is a method that overrides doSomething in MyTemplate.

instanceof-operator doSomething (Object obj) MyImpl. , .

0

, . , . ( ). :

abstract public class MyTemplate<T> {
    abstract public void doSomething(T t);
}

public class MyTemplateImpl extends MyTemplate<Object> {

    @Override
    public void doSomething(Object o) {
        System.out.println("Dealing with a generic Object");
    }
}

public class MyTemplateImplForStrings extends MyTemplate<String> {
    @Override
    public void doSomething(String s) {
        System.out.println("dealing with a String");
    }
}

, :

MyTemplateImplForStrings template = new MyTemplateImplForStrings();
template.doSomething("hello");  //prints ""dealing with a String"

MyTemplate<String> template = new MyTemplateImplForStrings();
template.doSomething("hello");  //prints ""dealing with a String"

: , String; ClassCastExceptions , .

0

java , Object, String. .

You can try the visitor template if you control all input classes or use reflection , which is slow / complex and easy to make mistakes.

0
source

Source: https://habr.com/ru/post/1784396/


All Articles