Overloading methods with derived types as parameters in Java

Suppose I have extended the existing code, but also avoid changing the code as much as possible

Somewhere in this code, there is a method that receives a certain type

Engine.method(Base b)

Now, I want to extend this feature So I extend base to a type named derived, which contains more data I need, and I also implement another type to receive derived and use it to do some different methods

Engine.method(Derived d)

But I don't want to change the original call to "method" In some way, I try to implement the correct type (base or derived) by using flags, but since the original call uses base, my new method will not be called

Base b = null;
if(flag) {
   b = new Derived()
} else{
   b = new Base()
} 
Engine.method(b)

The problem is now my engine Method (derived) will not be called I solved it by using casting

if(flag)
Engine.method((Derived)b)

But this is wrong and foolish Any suggestions?

I always do this:

if(flag) {
   Engine.methodForBase(new Base())
} else{
   Engine.methodForDerived(new Derived())
}

But can you think of something better?

thank you

Solution

This is because Java uses a single schedule This means that in your case, the method invoked depends on the referenced type "B", which is base, not the type of instance contained in "B" Therefore, the method xpto. Will always be called (Base b).

You really have to use the last method you write

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>