有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将self作为委托传递

我从类“mother”中创建了一个新对象“baby”,它实现了一个包含一个方法“feed”的接口(名称仅用于说明)

如何通过“baby”类的构造函数传递指向“mother”类的指针? 我希望baby类能够在其一生中的任何时间调用“feed”方法

到目前为止,我的尝试总是产生编译器错误

婴儿班的建设者

public Baby(String name, Mother mother) {
    this.mother=mother;
    this.name=name;
}

用于创建婴儿对象的代码(在母类内部)

Baby baby = new Baby("Brian",this);

共 (2) 个答案

  1. # 1 楼答案

    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的构造函数或非静态字段/方法中执行此任务

  2. # 2 楼答案

    在母类的主要方法中,实例化一个母类,然后将其传递给Baby

    public static void main(String[] args) {
      ....
      Mother mother = new Mother();
      Baby baby = new Baby("Brian", mother);
      ....
    }