我正在从类“mother”中创建一个新对象“baby”,它实现了一个包含一个方法“feed”的接口(interface)(名称仅供说明)。
如何通过“baby”类的构造函数传递指向“mother”类的指针? 我希望 baby 类能够在其整个生命周期中随时调用“feed”方法。
到目前为止,我所尝试的总是产生编译器错误。
baby类的构造函数
public Baby(String name, Mother mother) {
this.mother=mother;
this.name=name;
}
用于创建婴儿对象的代码(在 Mother 类中)
Baby baby = new Baby("Brian",this);
最佳答案
I'm trying to create the baby object from inside a static main method in the Mother class.
您不能在 static
上下文中传递 this
,例如作为 static
字段,在 static {}
初始值设定项中或在 static method()
方法中。静态上下文适用于类本身,而不适用于特定实例。
改为在 Mother
的构造函数或非静态字段/方法中完成这项工作。
关于java - 如何通过自己作为委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5985556/