我想创建一个非静态类,它的实例可以被它创建的实例访问,例如:
public class Foo {
private String name;
public Foo(String name) {
Bar bar = new Bar();
bar.getFooName();
this.name = name;
)
public String getName() {
return name;
}
}
public class Bar {
String getFooName() {
return Foo.toString(); //How do I get the Foo that created it?
}
}
public class Main {
public static void main(String[] args) {
new Foo("Steve");
new Foo("Bob");
}
}
如果我将 Foo.name 设为静态,则所有实例都将具有相同的名称。我可以在创建 Bar 时将 Foo 的实例作为变量传递,但这会变得困惑,假设 bar 生成了更多也想访问 Foo 的对象。是否有某种方法允许 Bar 和它创建的所有对象访问创建它们的 Foo 实例?
编辑:它的上下文是一个非静态主类,它创建许多不同类的实例。当可能存在主类的多个实例时,每个实例都需要能够找到由创建它的主实例创建的其他实例
最佳答案
您可以将 Foo
引用传递给 Bar
构造函数:
public class Foo
{
String name;
public Foo(String name) {
this.name = name;
Bar bar = new Bar(this);
}
public String getName () {
return this.name;
}
}
public class Bar
{
Foo creator;
public Bar (Foo creator) {
this.creator = creator;
}
String getFooName() {
return creator.getName();
}
}
不过,我不确定在 Foo
构造函数中创建一个 Bar
实例而不保留对它的引用有什么意义。
另一种选择是使 Bar
成为 Foo
的内部类:
public class Foo
{
String name;
public Foo(String name) {
this.name = name;
Bar bar = new Bar();
}
public String getName () {
return this.name;
}
public class Bar
{
public Bar () {
}
String getFooName() {
return getName();
}
}
}
这样每个 Bar
实例都将与 Foo
的封闭实例相关联。
关于java - 它创建的实例可访问的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54059969/