我正在用Java创建对象。它的属性之一是网格参考-整数x,y和z。

除了为每个变量创建变量之外,还有更好的方法来存储这些变量吗?

最佳答案

创建一个类似记录的类GridReference:

public class GridReference {

    public int x;

    public int y;

    public int z;

}


您可以将其实例化为:

GridReference gridReference = GridReference();


并通过以下方式分配各个值:

gridReference.x = 1;
gridReference.y = 0;
gridReference.z = 0;


可通过以下方式访问:

gridReference.x;
gridReference.y;
gridReference.z;


您可以将类充实为更安全的对象,如下所示:

public class GridReference {

    private final int _x;

    private final int _y;

    private final int _z;

    public GridReference(int x, int y, int z) {
        _x = x;
        _y = y;
        _z = z;
    }

    public getX() {
        return _x;
    }

    public getY() {
        return _y;
    }

    public getZ() {
        return _z;
    }

}


并将其实例化为:

GridReference gridReference = new GridReference(1, 0, 0);


同时分配值。这些可以通过以下方式访问:

gridReference.getX();
gridReference.getY();
gridReference.getZ();


(要更改值,您需要将引用重新分配给新的GridReference。)

09-30 19:55