gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:16:36 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com