How can I call a constructor properly in this case?

Tom :

I'm trying to call a constructor properly dealing with 3 different class but I'm not able to do it

public class B {

private final A a;

public B(A a) {
     this.a = a;
}
private final C c = new C(a);
}

I have the error "variable a might not have been initialized", I know a way to do it by putting a second argument in the B constructor and calling it in the main class B but is there any other way ?

daniu :

Sure.

public class B {

    private final A a;

    public B(A a) {
        this.a = a;
        c = new C(a);
    }
    private final C c;
}

The reason yours doesn't work is that initializers at declaration are executed before constructors.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132487&siteId=1