[英]To overload a method taking a base class and directing the extending classes method implementation
The logic below is all three classes AppleLeaf, MangoLeaf and BananaLeaf extend Leaf class. 下面的逻辑是AppleLeaf,MangoLeaf和BananaLeaf扩展Leaf类的所有三个类。 I have a method that takes a leaf object only.
我有一个只接受叶对象的方法。 It should redirect me to the methods below based on the class type correctly.
它应该根据类类型正确地将我重定向到下面的方法。 But I get error like, "The method handleLeaf(AppleLeaf) in the type main is not applicable for the arguments (Leaf)"
但是我收到错误消息,例如“类型main中的handleLeaf(AppleLeaf)方法不适用于参数(Leaf)”
public void main(String args[]){
for (Leaf leaf : leafList) {
handleLeaf(leaf);
}
}
private void handleLeaf(AppleLeaf node) {
String colour = leaf.getColour();
System.print.out(colour);
}
private void handleLeaf(MangoLeaf mLeaf) {
Int veins = mLeaf.getVeinCount;
System.print.out(veins);
}
private void handleLeaf(BananaLeaf bLeaf) {
Boolean withered = bLeaf.getTexture();
}
That's not quite how it works. 这不是很有效。 You've defined three methods, none of which take
Leaf
as a parameter. 您已经定义了三种方法,没有一种以
Leaf
为参数。 Each one takes a subclass of Leaf
, but we don't know which subclass of Leaf
the given argument might be. 每个对象都有一个
Leaf
的子类,但是我们不知道给定参数可能是Leaf
的子类。
One workaround is to make a delegating method such as: 一种解决方法是制作一种委托方法,例如:
private void handleLeaf(Leaf leaf) {
if(leaf instanceof AppleLeaf)
handleLeaf((AppleLeaf)leaf);
else if(leaf instanceof MangoLeaf)
handleLeaf((MangoLeaf)leaf);
...//And so on
}
You may consider reworking your logic in general, however. 但是,您可能会考虑重新构建逻辑。 Perhaps you can flip things around to define an abstract method in the
Leaf
class and have every leaf type handle itself in its own definition of the method. 也许您可以四处翻转以在
Leaf
类中定义一个抽象方法,并使每种叶子类型在其自己的方法定义中进行处理。
You cannot upcast automatically like that. 您不能像这样自动上架。 What you're looking for is dynamic method binding, which is not in Java.
您正在寻找的是动态方法绑定,这不是Java中的。 Java is a compiletime linked language, and hence, it will not compile/run.
Java是一种编译时链接的语言,因此它将无法编译/运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.