【问题标题】:ArrayLists and Polymorphism in JavaJava中的ArrayLists和多态性
【发布时间】:2019-03-14 11:16:48
【问题描述】:

我正在尝试在 Java 中实现一个垄断风格的游戏,作为学校项目的一部分,但我遇到了一个我无法解决的问题,或者似乎找到了我所遇到问题的答案。问题是我的代码中出现了 classCastException,我想我已经弄清楚了为什么会得到它(我最初试图将类型 Property 转换为下面的 newPosition 变量)但现在我需要找到一种方法来实现代码,这样我就可以避免它。

问题是我有一个超类Square,它有3个可能的子类PropertyGoFreeParking。我将我的电路板存储为 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


    【解决方案1】:

    如果您知道特定的 Square 是一个属性,请将其转换并分配给适当的类型。

    Property newPosition = (Property)board.get(player.getPosition());
    

    编辑:将来,您可能还想考虑将特定类型的 Square 的逻辑放入子类中。换句话说,像square.process(player) 这样的东西,其中Property、Go 和FreeParking 都以适当的逻辑实现process(player) 方法。这涉及到面向对象设计的更详细的概念,现在可能与您无关。

    【讨论】:

    • 感谢您的回复,我曾尝试像您描述的那样投射特定的正方形,但这导致了 classCastException。我以为是因为我试图将 Square 转换为 Property?
    • 确切的异常消息和堆栈跟踪是什么?
    • 线程“主”java.lang.ClassCastException 中的异常:monopoly.Go 无法转换为 Monopoly.Property ... 啊。那显然是问题所在
    【解决方案2】:

    希望这个sn-p能帮助你理解这个概念

    public static void main(String[] args) {
            Square newPosition = new Property();
            if (newPosition instanceof Property) {
                System.out.println("newPosition cast as Property");
                Property newPositionAsProperty = ((Property) newPosition);
                int newRent = newPositionAsProperty.getRent();
                // or
                newRent = ((Property) newPosition).getRent();
            }
            // To understand better
            if (newPosition instanceof Square) {
                System.out.println("newPosition instanceof Square");
                ((Square)newPosition).getName();
            }
            if (Square.class.isAssignableFrom(Property.class)) {
                System.out.println("Square.class.isAssignableFrom(Property.class)");
                ((Square)newPosition).getName();
            }
            if (Property.class.isInstance(newPosition)) {
                System.out.println("Property.class.isInstance(newPosition)");
                ((Property)newPosition).getName();
            }
            if (Square.class.isInstance(newPosition)) {
                System.out.println("Square.class.isInstance(newPosition)");
                ((Square)newPosition).getName();
            }
        }
    

    结果:

    newPosition cast as Property
    newPosition instanceof Square
    Square.class.isAssignableFrom(Property.class)
    Property.class.isInstance(newPosition)
    Square.class.isInstance(newPosition)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 2015-07-22
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多