java - 从参数中包含共享对象的另一个构造函数调用构造函数 init

标签 java constructor

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

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 实例。

有什么想法可以解决这个问题吗?

最佳答案

为了使用this构造函数,它必须是构造函数的第一行。类似的东西,

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

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

注意:如果您想防止外部调用,您可以将SomeClass(Foo) 构造函数设为private

关于java - 从参数中包含共享对象的另一个构造函数调用构造函数 init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838957/

相关文章:

Java乘法错误

c++ - 为什么 std::pair 不可构造?

java - 调用当前类或父类(super class)的重载构造函数

actionscript-3 - Flash AS3 : 1026 Error: Constructor functions must be instance methods

java - 哪些 servlet 不是 Web 应用程序的一部分

java - 从一类 Corba 创建多个服务器时出现问题

java - Android getDeclaredConstructors() 对于 Android 28 (Pie) 的行为有所不同

Scala - 构造函数中无法识别方法

java - Glassfish 嵌入了 ScatteredArchive 和 Web 内容

java - 我应该为每个线程创建一个连接吗?