我正在尝试制作一个定位不同城市的小程序,作为我的第一个Java项目。
我想从类'City‘访问我的类'GPS’的变量,但我总是得到这个错误:赋值的左边必须是一个变量。任何人都可以向我解释我在这里做错了什么,以及如何在未来避免这样的错误?
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}(我希望将变量保留为私有)
这个类'Citiy‘应该有坐标:
class City {
Gps where;
Location(int x, int y, int z) {
where.getX() = x;
where.getY() = y; //The Error Here
where.getZ() = z;
}
}发布于 2017-05-09 03:02:51
错误不言而喻:您不能为不是字段或变量的对象赋值。Getter用于获取存储在类中的值。Java使用setter来处理存储值的问题:
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}现在,您可以通过调用setter来设置值:
City(int x, int y, int z) {
where.setX(x);
...
}然而,这种解决方案并不理想,因为它使Gps变得可变。您可以通过添加构造函数使其保持不可变:
public Gps(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}现在City可以一次设置where:
City(int x, int y, int z) {
where = new Gps(x, y, z);
}发布于 2017-05-09 03:04:08
不要使用getter设置属性。应该这样做:
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setZ(int z) {
this.z = z;
}
}
class City {
Gps where;
City(int x, int y, int z) {
this.where = new Gps();
where.setX(x);
where.setY(y);
where.setZ(z);
}
}https://stackoverflow.com/questions/43855307
复制相似问题