gpt4 book ai didi

java - 在 Java 中访问组合对象

转载 作者:行者123 更新时间:2023-12-01 11:41:34 24 4
gpt4 key购买 nike

Java 新手。

我有一个下面 Player 类的实例player1。

Player player1 = new Player(0,0);

在 Player 类中,我编写了一个 Coord 类型的对象坐标(定义如下)。当我实例化上面的player1时,“玩家位于坐标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());

我做错了什么?

最佳答案

您没有将 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());

您还可以在 Coord 类中重写 toString(),然后您可以说

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

关于java - 在 Java 中访问组合对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com