将此传递给从接口实现的方法

时间:2017-07-13 02:15:49

标签: java interface this

我想知道将“this”作为参数传递给从接口实现的方法是否正确。

我想用CreateOutput方法实现A类。 我使用Output方法定义了接口F,并使用实现此接口的B类定义了接口F. A类的构造函数接收F类型的对象并将其存储在私有变量中(该对象是B类的等级)。

要产生输出,我需要传递给Output方法“this”,让B类访问要输出的数据。

这是对的吗?

1 个答案:

答案 0 :(得分:-1)

这是对的。

public class A {
    private F f;

    A(F f) {
        this.f = f;
    }

    void CreateOutput() {
        f.Output(this);
    }
}

interface F {
    void Output(Object obj);
}

public class B implements F {
    @Override
    public void Output(Object obj) {
    }
}

A a = new A(new B());
a.CreateOutput();
相关问题