在Java中访问组合对象

时间:2015-04-07 00:39:56

标签: java composition

Java新手。

我有一个Player类的实例播放器1。

Player player1 = new Player(0,0);

在Player类中,我创建了一个Coord类型的对象坐标(在下面定义)。当我实例化上面的播放器1"播放器在坐标0,0"按预期显示。

public class Player extends Entity { 
    public Coord coordinate;
    public Player(int x, int y) {
        Coord coordinate = new Coord(x,y);
        System.out.println(“Player is at coordinate “ + coordinate.getX() + “,” 
        + coordinate.getY());
    }
}

Coord课程定义如下。

public class Coord {
    private int x;
    private int y;

    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

当我在实例化player1后尝试访问obj及其各自的方法时出现问题。当我尝试访问坐标时,我得到一个NullPointerException错误。

Player player1 = new Player(0,0);

System.out.println(“Player is at coordinate “ + player1.coordinate.getX() + 
“,” + player1.coordinate.getY());

我做错了什么?

1 个答案:

答案 0 :(得分:1)

你并没有让Coord obj;成为你班级的一个领域。这可能就像

这样简单
public class Player extends Entity { 
    Coord obj;
    public Player(int x, int y) {
        obj = new Coord(x,y);
        System.out.println(“Player is at coordinate “ + obj.getX() + “,” 
        + obj.getY());
    }
}

请注意,obj是一个糟糕的字段名称,并且它具有默认的级别访问权限。改善这种情况的一种方法可能是

public class Player extends Entity { 
    private Coord coordinates;
    public Player(int x, int y) {
        coordinates = new Coord(x,y);
        System.out.println(“Player is at coordinate “ + obj.getX() + “,” 
        + obj.getY());
    }
    public Coord getCoordinates() {
        return coordinates;
    }
}

然后你可以像

一样使用它
Player player1 = new Player(0,0);

System.out.println(“Player is at coordinate “ 
    + player1.getCoordinates().getX() 
    + “,” + player1.getCoordinates().getY());

您也可以覆盖toString()课程中的Coord,然后您可以说

System.out.println(“Player is at coordinate “ 
    + player1.getCoordinates());