简体   繁体   English

Java将超类类型的对象指向适当的方法

[英]Java directing object of type superclass to appropriate method

In my Java code I have a class 'Feature' which is extended by 'ContinuousFeature' and 'DiscreteFeature'.在我的 Java 代码中,我有一个类“Feature”,它由“ContinuousFeature”和“DiscreteFeature”扩展。 I have methods:我有方法:

Calculate(ContinuousFeature c)

and

Calculate(DiscreteFeature d)

I have an ArrayList containing generic 'Feature' objects (both Discrete and Continuous), and am trying to do something like:我有一个包含通用“功能”对象(离散和连续)的 ArrayList,我正在尝试执行以下操作:

for(Feature f : features) {

    Calculate(f);

}

Hoping that they would automatically be directed to the appropriate method.希望他们会自动被引导到适当的方法。 However, IntelliJ is informing me that it cannot find a method Calculate for type 'Feature'.但是,IntelliJ 通知我它找不到“功能”类型的计算方法。 Any advice?有什么建议吗? :) :)

You can change code like this.您可以像这样更改代码。

for(Feature f : features) {
if(f instanceof ContinuousFeature)
    Calculate((ContinuousFeature)f);
else {
 Calculate((DiscreteFeature)f);
}

} }

如果你不喜欢使用instanceof ,我建议在它们各自的类中添加像isContinuousFeature()这样的方法,返回一个布尔类型并每次检查,它可能不是最干净的,但它会得到你想要的。

You could create in your Feature.java something like你可以在你的 Feature.java 中创建类似的东西

public void Calculate(Feature feature){}

And I think that line could solve your problem.我认为这条线可以解决你的问题。 Or maybe make the class abstract and something like:或者可能使类抽象,例如:

public abstract void Calculate(Feature feature);

would be enough.就足够了。 And I think it would be cleaner.而且我认为它会更干净。 But that's just my opinion.但那只是我的个人意见。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM