我在ArrayList中放置了不同的类,我想访问我的类的方法

时间:2019-06-28 18:14:49

标签: java class arraylist methods

public class MyEmpire
{
    private ArrayList <Property> properties;
    private Utility [] utilities;
    private Corner [] fourCorners;

    public MyEmpire ()
    {
        this.properties = new ArrayList <Property> ();
        this.utilities = new Utility [2];
        this.fourCorners = new Corner [4];

        // just examples not all initializations are here
        properties.add(new Property("Almond Drive", 2.5));
        properties.add(new Property("Kasoy Street", 3.0));
        properties.add(new Property("Rodeo Drive", 3.5));

        fourCorners[0] = new Corner("START");
        fourCorners[1] = new Corner("Community Service");
        fourCorners[2] = new Corner("Jail");
        fourCorners[3] = new Corner("Free Parking");

        utilities[0] = new Utility("Electric");
        utilities[1] = new Utility("Water");
    }

public void defaultBoard ()
{
    board.add(fourCorners[0]);
    board.add(properties.get(0));
    board.add(properties.get(1));
}

public void Display ()
{
    defaultBoard ();

    System.out.println(board.get(0).getName ());
    // i dont know how to access the getName method of Property class. 
}

在arraylist板上,我放置了不同的类。我想知道 我如何获取该属性的名称,例如不使用 properties.get(i).getName()

public class Property
{
    private String name;
    private double multiplier;

    public Property (String name, double multiplier)
    {
        this.name = name;
        this.multiplier = multiplier;
    }

    public String getName ()
    {
        return name;
    }
}

我试图将不同的类放在一个arraylist中,然后我想访问这些类的方法,但我不知道如何

2 个答案:

答案 0 :(得分:1)

您应该使用接口定义board的任何成员都需要实现的功能。 在这种情况下,您似乎希望所有人都至少拥有一种获取其姓名的方法。我也希望您可能想知道当玩家着手于棋盘元素时会发生什么。

这是您可以使用的模板(椭圆形供您填写):

public class Main {

    public interface BoardElement {
        /** The name of this BoardElement */
        public String getName();

        /** What happens when Player lands on this BoardElement */
        public void onLanding(Player player);

        ...
    }

    public class Player { ... }
    public class Property implements BoardElement { ...  }
    public class Utility implements BoardElement { ... }
    public class Corner implements BoardElement { ... }

    public static void display () {
        List<BoardElement> board = ...;
        System.out.println(board.get(0).getName());
        for(BoardElement element : board) {
            System.out.println(element.getName());
        }
    }
}

答案 1 :(得分:0)

您只是错过了需要投射对象的事实吗?

((Property) board.get(0)).getName()