Method overloading using derived types as parameters in Java

后端 未结 3 1452
感动是毒
感动是毒 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: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);
        ...
    }
    

提交回复
热议问题