java - 如何通过自己作为委托(delegate)

标签 java delegates

我正在从类“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/

上一篇:java - 多个 JButton

下一篇:java - 特征检测

相关文章:

java - 如何将 Map 中的值与流相加?

Java JOGL 纹理对象未翻译

java - 在 selenium Webdriver 中从父窗口切换到子窗口时出错,反之亦然

java - HSQLDB 正在吞噬我所有的内存

c# - 如何创建算法类型?

ios - 澄清 UIViewController<Delegate> *_variable; iAdSuite 选项卡式示例 (iOS) 中的声明

objective-c - 如何处理自定义 UIViewController 委托(delegate) (ARC)?

c# - 在运行时(不是编译时)用具有不同签名的委托(delegate)包装委托(delegate)

java - "constructor statement"和 "declaration statement"是描述这些语句的正确名称吗?

c# - 用于 OnSelect 和 OnDeselect 目的的委托(delegate)