我处于将静态字段变量引用到自定义类的位置。我需要使用它引用的类中的方法对变量进行更改。我无法实例化正在构建的类。简化示例:
public class House {
private static MaterialsRequired matsReq = new MaterialsRequired();
private String size;
private House(String size) {
this.size = size;
}
public static MaterialsRequired getMaterialsRequired() {
}
public static void Build(String size) {
new House(size); //Do I need to put 'this(size)' here?
//some code here to expend the materials required factored based on size.
}
要建造房子,我需要知道所需的材料(标准尺寸)。要知道需要的材料,我需要调用 MaterialsRequired 的 addMaterial() 方法。我该怎么办?
编辑:我需要在 matsReq 上重复调用 addMaterial() 方法。也许十次。当我调用 House.build() 时,我希望 matsReq 已被方法调用更改(如果我的问题不具体)。此外,每次调用 build() 或 getMaterialsRequired() 方法时只设置所需的材料也不能让我满意。
问题已经回答了!解决方案:
private static MaterialsRequired matsReq = new MaterialsRequired();
static {
matsReq.addMaterial(mat1);
matsReq.addMaterial(mat2);
matsReq.addMaterial(mat3);
}
private String size;