New to Java.
I have an instance player1 of the Player class below.
Player player1 = new Player(0,0);
Inside the Player class I have composed an object coordinate of type Coord (defined below). When I instantiate player1 above "Player is at coordinate 0,0" is displayed as expected.
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());
}
}
The Coord class is defined as follows.
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;
}
}
The problem arises when I try to access obj and its respective methods after I instantiate player1. When I try to access coordinate I get a NullPointerException error.
Player player1 = new Player(0,0);
System.out.println(“Player is at coordinate “ + player1.coordinate.getX() +
“,” + player1.coordinate.getY());
What am I doing wrong?