我需要使用多态性在play()方法中调用move()方法。我不知道该怎么做。我的程序中的其他一切都能正常工作,我唯一的问题是如何在play()方法中使用move()方法。Move()方法在另一个名为“Human”的类中,这个类也使用"player“接口。该方法可以正常工作。
public interface Players {
int move(); // returns an int that is given by user
}
// Method that I need call the move() method in
// You may ignore the rest of the code expect where I commented
class Nim implements Players {
private int marbles = 0;
private int take = 0;
public void play() {
playerName = obj2.getName();
System.out.println("Player " + playerName);
turn();
getComp();
int removeMarbles = 0;
System.out.println("\nNumber of marbles: " + marbles);
Pile obj = new Pile();
while (marbles > 0) {
if (turn % 2 != 0) {
take = move() // need to call move method using polymorphism, ***code does not work just to show where I need help
System.out.println(playerName + " took " + take + " marble(s)");
marbles = marbles - take;
System.out.println("There are " + marbles + " marbles left.");
}
if (turn % 2 == 0) {
if (compName.equals("Dumb")) {
removeMarbles = (int)(Math.random() * (marbles / 2) + 1);
System.out.println("\nThe computer took " + removeMarbles + " marble(s)");
marbles -= removeMarbles;
}
if (compName.equals("Smart")) {
int pile = marbles;
int power = 2;
if (marbles <= power) {
removeMarbles = 1;
}
if (marbles > power) {
while (power < marbles) {
power = power * 2;
}
removeMarbles = ((power / 2) - 1);
}
marbles = removeMarbles;
System.out.println("\nThe computer took " + (pile - removeMarbles) + " marble(s)");
}
System.out.println("There are " + marbles + " marbles left.\n");
}
if (marbles == 0) {
if (turn % 2 != 0) {
System.out.println("\nThe computer is the winner!!!!");
} else {
System.out.println("\n" + playerName + " is the winner!!!!");
}
}
turn++;
}
}
}发布于 2015-03-03 13:26:47
Interfaces are contracts describing the group of related methods with empty bodies.您需要在子类中实现move()方法,然后使用任何其他功能覆盖该方法:
public int move(){
// Implements interface .move();
System.out.println("Nim .move()");
}从Docs
如果要在播放器中实现该方法,则不能将其作为接口实现,因为该行为将被实现该接口的方法覆盖。相反,您应该考虑使用super关键字的抽象类结构:
从Docs
发布于 2015-03-03 13:30:38
首先,您需要在Human类中实现该方法,如下所示
public class Humans implements Players {
public int move(){
// your logic here
}
}然后,您可以使用object调用该方法,如下所示
Players ob = new Humans();
take = ob.move();发布于 2015-03-03 13:10:59
目前,您的move()被声明为一个变量。你会想让它成为接口中的一个方法,这样你就不需要强制转换就可以调用它。
基本上,
int move();应该看起来像这样:
public int move(){
// your code here;
}https://stackoverflow.com/questions/28824402
复制相似问题