该方法不适用于参数

Jay*_*ers 1 java interface

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

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");
   }
Run Code Online (Sandbox Code Playgroud)

主要是我有这个:

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 
Run Code Online (Sandbox Code Playgroud)

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

das*_*ght 5

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

具体来说,编译器不知道t[0]是a Car还是a 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); }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以按如下方式拨打电话:

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); 
Run Code Online (Sandbox Code Playgroud)

这种技术通常称为访客模式.