首页 > 解决方案 > 从另一个构造函数调用构造函数 init,其参数中包含共享对象

问题描述

所以,我有一个具有以下构造函数的类:

public SomeClass() {
    this.foo = new Foo();
    this.bar = new Bar(foo); // Bar construction requires foo
}

public SomeClass(Foo foo, Bar bar) {
    this.foo = foo;
    this.bar = bar;
}

现在,我想通过更改默认构造函数来重新利用第二个构造函数,例如:

public SomeClass() {
    Foo = new Foo();
    this(foo, new Bar(foo));
}

但这不起作用,因为我得到

Error:(24, 21) java: call to this must be first statement in constructor

请注意,我不想有 2 个单独的 foo 实例。

任何想法如何解决这种情况?

标签: javaconstructor

解决方案


为了使用this构造函数,它必须是构造函数的第一行。就像是,

public SomeClass() {
    this(new Foo());
}

public SomeClass(Foo foo) {
    this(foo, new Bar(foo));
}

注意:如果要防止外部调用,可以创建SomeClass(Foo)构造函数。private


推荐阅读