我正在尝试创建一个将不同城市定位为我的第一个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;
}
}
错误不言而喻:您无法为不是字段或变量的内容赋值。 Getters用于获取存储在类中的值。 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);
}
不要使用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);
}
}