gpt4 book ai didi

java - 该方法不适用于参数

转载 作者:行者123 更新时间:2023-11-29 07:28:15 25 4
gpt4 key购买 nike

我有一个接口(interface)和两个实现它的类,第三个类有两个方法——一个获取第一个类对象作为参数,第二个获取另一个。我有一个包含两种类型对象的 vector ,我想在每个元素上使用第三个函数的方法而不必转换类型,因为我不知道每个 vector 元素是什么类型。我怎样才能做到这一点?这是代码:

public interface Transport {
}

public class Car implements Transport {
}

public class Bike implements Transport {
}

public class Operation {
public void operation(Car c) {
System.out.println("1");
}

public void operation(Bike b) {
System.out.println("2");
}

主要是我有这个:

Transport[] t = new Transport[3];
t[0] = new Car();
t[1] = new Bike();
t[2] = new Car();
Operation op = new Operation();
op.operation(t[0]); // here I get the error - method not applicable for arguments

这段代码是我所做的简化版本,为了更容易阅读,不仅有三个元素,而且它们是根据它获得的输入在 for 循环中创建的。

最佳答案

您正试图在编译器不知道表达式的运行时类型的情况下使用方法重载。

具体来说,编译器不知道 t[0]Car 还是 Bike,因此会发出错误。

您可以通过反转调用来解决此问题:为 Transport 提供调用 operate 的方法,然后改为调用它:

public interface Transport {
void performOperation(Operation op);
}

public class Car implements Transport {
public void performOperation(Operation op) { op.operate(this); }
}

public class Bike implements Transport {
public void performOperation(Operation op) { op.operate(this); }
}

现在可以调用如下:

Transport[] t = new Transport[3];
t[0] = new Car();
t[1] = new Bike();
t[2] = new Car();
Operation op = new Operation();
t[0].performOperation(op);

此技术通常称为 Visitor Pattern .

关于java - 该方法不适用于参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com