Java 如何正确添加接口作为构造函数参数?
我已经在我的主方法中初始化了这个Game()构造函数,该方法将2个接口作为参数:Java 如何正确添加接口作为构造函数参数?,java,lambda,Java,Lambda,我已经在我的主方法中初始化了这个Game()构造函数,该方法将2个接口作为参数: Game game = new Game( (player, bridge) -> { if (player instanceof HumanPlayer) return true; if (player instanceof RobotPlayer && b
Game game = new Game(
(player, bridge) -> {
if (player instanceof HumanPlayer)
return true;
if (player instanceof RobotPlayer && bridge instanceof FakeBridge)
return true;
return false;
},
(player) -> {
if (player instanceof HumanPlayer) {
HumanPlayer hPlayer = (HumanPlayer) player;
hPlayer.updateAge(hPlayer.age() + 1);
Car car = (Car) hPlayer.vehicle();
car.setGas(car.gas());
} else if (player instanceof RobotPlayer) {
RobotPlayer rPlayer = (RobotPlayer) player;
rPlayer.updatePower(rPlayer.power() - 5);
}
System.out.println(player);
}
);
下面是我在Game()的构造函数中提供的两个接口
下面是Game类的构造函数:
public Game(Initialize initial, Interface2 player ) {
this.initial = initial;
this.player = player1;
}
由于某些原因,它仍然给我一个错误:
构造器游戏((玩家,桥牌)->{},(玩家)->
{}未定义
编辑:以下是我提供的两个界面:
public interface Initialize {
boolean constraint(Player player, Bridge bridge);
}
及
您的问题是关于签名与接口不匹配的第二个声明:此编译:
public void run() {
Game game = new Game((player, bridge) -> {
return true;
}, (player) -> {
return true;
});
}
public class Bridge {
}
public class Player {
}
public interface Initialize {
boolean constraint(Player player, Bridge bridge);
}
public interface Interface2 {
boolean constraint(Player player);
}
public class Game {
private Initialize initial;
private Interface2 player;
public Game(Initialize initial, Interface2 player) {
this.initial = initial;
this.player = player;
}
}
您的第二个声明缺少返回类型您的问题是关于签名与接口不匹配的第二个声明:此编译:
public void run() {
Game game = new Game((player, bridge) -> {
return true;
}, (player) -> {
return true;
});
}
public class Bridge {
}
public class Player {
}
public interface Initialize {
boolean constraint(Player player, Bridge bridge);
}
public interface Interface2 {
boolean constraint(Player player);
}
public class Game {
private Initialize initial;
private Interface2 player;
public Game(Initialize initial, Interface2 player) {
this.initial = initial;
this.player = player;
}
}
在第二个声明中缺少返回类型您缺少函数
(player)->{…}
的返回语句,但如果不想返回值,请使用接口
也就是说,我建议使用,而不是创建自己的精确副本。您缺少函数
(player)->{…}
的返回语句,但是如果您不想返回值,请使用接口
也就是说,我建议使用,而不是创建自己的精确副本。请显示接口定义。我已将它们添加到两个同名接口中?我的错!我修复了它…您缺少函数
(player)->{…}
的返回语句,但是如果您不想返回值,请使用消费者
接口。请显示接口定义。我已将它们添加到具有相同名称的后两个接口中?我的错!我修复了它…您缺少函数(player)->{…}
的返回语句,但是如果您不想返回值,请使用使用者
接口。
public void run() {
Game game = new Game((player, bridge) -> {
return true;
}, (player) -> {
return true;
});
}
public class Bridge {
}
public class Player {
}
public interface Initialize {
boolean constraint(Player player, Bridge bridge);
}
public interface Interface2 {
boolean constraint(Player player);
}
public class Game {
private Initialize initial;
private Interface2 player;
public Game(Initialize initial, Interface2 player) {
this.initial = initial;
this.player = player;
}
}