【发布时间】:2019-03-14 11:16:48
【问题描述】:
我正在尝试在 Java 中实现一个垄断风格的游戏,作为学校项目的一部分,但我遇到了一个我无法解决的问题,或者似乎找到了我所遇到问题的答案。问题是我的代码中出现了 classCastException,我想我已经弄清楚了为什么会得到它(我最初试图将类型 Property 转换为下面的 newPosition 变量)但现在我需要找到一种方法来实现代码,这样我就可以避免它。
问题是我有一个超类Square,它有3个可能的子类Property、Go和FreeParking。我将我的电路板存储为 ArrayList,但我需要访问与 Property 对象相关的方法来计算租金等。如果我从 ArrayList 访问其类型为 Square 的属性,我如何访问这些方法。
如果这没有太大意义,请提前道歉。
public abstract class Square {
private String name;
private boolean isAvailable;
private Player owner;
//getters and setters
}
public class Property extends Square{
private String colour;
private int buyHouset;
private int rent1House;
private int rent2House;
private int rent3House;
private int rentHotel;
private int numHouses;
private int rent;
private int price;
//getters and setters
}
public static void takeTurn(Player player, Dice die, ArrayList<Square> board) {
System.out.println(player.getGamertag() + "'s turn");
//get value from roll of die
int move = askToRoll();
String gamertag = player.getGamertag();
//if player does not quit continue with turn
if(move > 0) {
//get player current position and add roll of die
int newSpaceIndex = player.getPosition() + move;
//if players new position exceeds the array of squares, return to 0 index and add remainder
//add credits for passing Go
//else update position
if (newSpaceIndex > 11) {
player.setPosition(newSpaceIndex - 12);
Go.passGoAction(player);
}else {
player.setPosition(newSpaceIndex);
}
if(player.getPosition() == 1) {
Square newPosition = board.get(player.getPosition());
System.out.println(gamertag + " new position " + newPosition.getName());
}else if(player.getPosition() == 6) {
FreeParking.freeParkingAction();
} else {
Square newPosition = board.get(player.getPosition());
System.out.println("____________________");
System.out.println("Land on " + newPosition.getName());
if(newPosition.getOwner() != null) {
Player owner = newPosition.getOwner();
/* *****THIS IS WHERE THE ERROR IS STEMING FROM*****
*THE newPosition.getRent() method can not be accessed as newPosition
*is defines as Square
*/
System.out.println(owner.getGamertag() + " demands you pay " + newPosition.getRent() + " credits!");
}else {
System.out.println("What would you like to do now? ...\n"
+ "1. Buy property\n"
+ "2. End turn");
int input = in.nextInt();
boolean valid = false;
do {
switch(input) {
case 1:
System.out.println("You now own controlling stock of " + newPosition.getName());
player.setOwnsProperty(newPosition);
newPosition.setOwner(player);
valid = true;
break;
case 2:
System.out.println("Ending turn");
valid=true;
break;
default:
System.out.println("Invalid input, please select one of the options 1-2");
valid = false;
break;
}
}while(!valid);
}
}
}
System.out.println("END TURN: " + player);
System.out.println();
}
【问题讨论】:
标签: java inheritance arraylist polymorphism