Method overloading using derived types as parameters in Java

后端 未结 3 1449
感动是毒
感动是毒 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 {
        void method(T argument);
    }
    

    And have implementations for Base and Derived like this:

    class BaseEngine implements Engine {
        @Override
        public void method(Base argument) { ... }
    }
    
    class DerivedEngine implements Engine {
        @Override
        public void method(Derived argument) { ... }
    }
    

提交回复
热议问题