在 Main class 或 main 方法中修改实例变量
Modify an instance variable within the Main class or main method
我希望能够在某些时候通过主驱动程序 class 修改 class 中构造函数中定义的局部变量的值,而 运行 程序.我怎样才能做到这一点?
这是我正在使用的构造函数示例。
public Scale()
{
weight = 0;
unit = "kg";
}
我想在运行驱动中的程序中修改某个点的权重值。
听起来您想给 class 一个方法,允许外部代码能够更改或 "mutate" class 字段的状态.这样的"mutator"方法在Java中常用,比如"setter"方法。这里,public void setWeight(int weight)
:
public void setWeight(int weight) {
this.weight = weight;
}
最好的方法可能是通过一种方法。它可以是像 setWeight()
这样简单的东西,也可以是更复杂的东西,比如将项目添加到秤的方法...
public class Scale {
private float weight = 0;
private String unit = "kg";
public void setWeight(float weight) {
this.weight = weight;
}
public void addItem(Item i) { // Assumes that Item is an interface defined somewhere else...
this.weight += i.getWeight();
}
public static void main(String[] args) {
Scale s = new Scale();
s.setWeight(4.0F); // sets the weight to 4kg
s.addItem(new Item() {
@Override
public float getWeight() {
return 2.0F;
}
}); // Adds 2kg to the previous 4kg -- total of 6kg
}
}
我希望能够在某些时候通过主驱动程序 class 修改 class 中构造函数中定义的局部变量的值,而 运行 程序.我怎样才能做到这一点?
这是我正在使用的构造函数示例。
public Scale()
{
weight = 0;
unit = "kg";
}
我想在运行驱动中的程序中修改某个点的权重值。
听起来您想给 class 一个方法,允许外部代码能够更改或 "mutate" class 字段的状态.这样的"mutator"方法在Java中常用,比如"setter"方法。这里,public void setWeight(int weight)
:
public void setWeight(int weight) {
this.weight = weight;
}
最好的方法可能是通过一种方法。它可以是像 setWeight()
这样简单的东西,也可以是更复杂的东西,比如将项目添加到秤的方法...
public class Scale {
private float weight = 0;
private String unit = "kg";
public void setWeight(float weight) {
this.weight = weight;
}
public void addItem(Item i) { // Assumes that Item is an interface defined somewhere else...
this.weight += i.getWeight();
}
public static void main(String[] args) {
Scale s = new Scale();
s.setWeight(4.0F); // sets the weight to 4kg
s.addItem(new Item() {
@Override
public float getWeight() {
return 2.0F;
}
}); // Adds 2kg to the previous 4kg -- total of 6kg
}
}