In Java, which is statically typed, there is no direct equivalent of the JavaScript ad-hoc object presented1.
Instead, one would create a [Player] class representing the "object" and then instantiate and use one or more instances. This class/instance approach, along with subtyping, is the core of the Java OOP model; there is no escape or viable alternative in Java - when using Java, write Java.
public class Player {
protected int x;
protected int y;
// and maybe `cloned`, etc.
// maybe an "action"
public void move(int x, int y) {
this.x = x;
this.y = y;
}
// maybe a getter/setter
// (although `move` above may obsolete the use of such setter)
public int getX () { return x; }
public void setX (int x) { this.x = x; }
// and other relevant methods ..
};
And usage later might look like
// create new instance of class/type
Player player = new Player();
// manipulate and use
player.move(19, 81);
drawImage(player.getX(), player.getY());
While there is a "setter" provided in the Player class, only the "getter" was required for the usage; I prefer to use actions (e.g. move
), and reducing mutable state when applicable, instead of allowing direct field manipulation as this can increase encapsulation. In any case, see How do getters and setters work? wrt this tangent.
Also consider "programming to interfaces"; for a real implementation I would likely have an Entity interface, implemented by the Player class, which understands positional movements and location. (While this is even more tangential, I wish that I had started programming "OOP" in this manner and I try to eschew type contracts based on implementing class or subtype relations!)
1 This is true of Java, but it is not inherent of static typing; for instance, C# has anonymous types (albeit the static typing and inference is limited within the function) and different languages support strongly-typed records and/or structural typing and/or dynamic typing in an otherwise statically-typed language. Java, however, requires that such is codified into a class for support at the language level.