Method overloading using derived types as parameters in Java

后端 未结 3 1448
感动是毒
感动是毒 2021-01-14 15:21

Let\'s say I have existing code which I want to extend but also to avoid changing it as much as possible.

Somewhere around this code there is a method that receives

相关标签:
3条回答
  • 2021-01-14 15:32

    Write this:

    class Engine {
        public static void method(Base argument) {
            if (argument instanceof Derived) {
                // ...
            }
            else {
                // ...
            }
        }
    }
    

    But probably, you should extend your Engine class to allow for more polymorphism, e.g. do something like this:

    interface Engine<T extends Base> {
        void method(T argument);
    }
    

    And have implementations for Base and Derived like this:

    class BaseEngine implements Engine<Base> {
        @Override
        public void method(Base argument) { ... }
    }
    
    class DerivedEngine implements Engine<Derived> {
        @Override
        public void method(Derived argument) { ... }
    }
    
    0 讨论(0)
  • 2021-01-14 15:38

    Why not simply call the method with a parameter of the correct type?

    Base b = null;
    if (flag) {
        Derived d = new Derived()
        Engine.method(d); // so the correct method will be used for Derived
        b = d;
    } else{
        b = new Base()
        Engine.method(b) 
    }
    

    You could also consider reusing the method(Base b):

    public void method(Derived d) {
        method((Base)b);
        ...
    }
    
    0 讨论(0)
  • 2021-01-14 15:43

    That happens because Java uses single dispatch. This ends meaning that in your case, the method called depends on the type of reference "b", which is Base, and not on the type of the instance that "b" holds. Therefore, method xpto.(Base b) will always be called.

    You really have to cast it or use the last approach you wrote.

    0 讨论(0)
提交回复
热议问题