我试图在SiloManager类中创建Silo类的两个对象,以便可以访问这两个对象的方法。但是我似乎无法使SiloManager构造函数正常工作,也无法正确地实例化这些类。 (我是Java的初学者)。这是我的代码:

public class GrainSiloManager {

    public GrainSilo silo1 = new GrainSilo(100);
    public GrainSilo silo2 = new GrainSilo(50);


    public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
        this.silo1 = silo1;
        this.silo2 = silo2;
    }

    private void showStatus() {
        System.out.println("The current grain in silo1 is: " + silo1.getGrain());
        System.out.println("The current grain in silo2 is: " + silo2.getGrain());
    }

}


正如我说的我是一名初学者,所以请放轻松,谢谢您的帮助。

最佳答案

public GrainSilo silo1 = new GrainSilo(100);
public GrainSilo silo2 = new GrainSilo(50);


public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
    this.silo1 = silo1;
    this.silo2 = silo2;
}


这将被编译为:

public GrainSilo silo1;
public GrainSilo silo2;


public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
    this.silo1 = new GrainSilo(100);
    this.silo2 = new GrainSilo(50);
    this.silo1 = silo1;
    this.silo2 = silo2;
}


如您所见,这几乎没有意义。您正在使用传递到构造函数中的对象覆盖您制作的对象。

09-12 17:34