使用派生类型作为Java中的参数进行方法重载 [英] Method overloading using derived types as parameters in Java

查看:112
本文介绍了使用派生类型作为Java中的参数进行方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经扩展了现有代码,但也避免尽可能地更改代码。

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 some type.

Engine.method(Base b) 

现在,我想扩展此功能。所以我将Base扩展为一个名为Derived的类型,它包含了我需要的更多数据,并且我还实现了另一个接收Derived类型并使用它做一些不同的方法。

Now, I want to extend this functionality. So I extends Base into a type called Derived which holds some more data I need and I also implements another method that receives the Derived type and do something different with it.

Engine.method(Derived d)

但我不想将原来的呼叫改为方法。我以某种方式设法通过使用标志来实现正确的类型(Base或Derived),但由于原始调用采用Base,因此我的新方法将不会被调用。

But I don't want to change the original call to "method". I somehow managed to instansiate the correct type (Base or Derived) by using a flag but since the original call is taking the Base then my new method will not be called.

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

问题是现在我的Engine.method(Derived d)不会被调用。我通过使用投射来解决它

The problem is that now my Engine.method(Derived d) will not be called. I worked-around it by using casting

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

但那是错误和愚蠢的。有什么建议吗?

But that's wrong and stupid. Any suggestions?

我总能这样做:

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

但你能想到更好的东西吗?

But can you think of something better?

谢谢

推荐答案

这是因为Java使用单一调度。这结束意味着在您的情况下,调用的方法取决于引用类型b,它是Base,而不是b所包含的实例的类型。因此,方法xpto。(基础b)将始终被调用。

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.

这篇关于使用派生类型作为Java中的参数进行方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆