传递实现接口的内部类

时间:2011-06-16 09:39:14

标签: java inheritance inner-classes

说我有以下内容:

public class A {
  //stuff
  public class B implements I {}
}

public interface I {}

public class Foo {
  int bar(I i) {}
}

当我尝试将A的实例传递给A类主体内的Foo.bar()时,为什么Java会给我一个“不适用于类型...”的构建错误?

内部类不被认为是I的正确实现,因为它包含在顶级类中吗?

干杯,戴夫。

4 个答案:

答案 0 :(得分:3)

我怀疑你可能有两个不同的I接口。确保在两个文件中导入相同的文件。

如果您不小心使用两个名称相同的接口,这是您从Eclipse获得的确切错误。

The method bar(I) in the type Foo is not applicable for the arguments (A.B)

作为参考,这对我编译很好:

class A {
    // stuff
    public void test() {
        new Foo().bar(new B());
    }

    public class B implements I {
    }
}

interface I {
}

class Foo {
    int bar(I i) {
        return 0;    // note that you need a return value for it to compile.
    }
}

答案 1 :(得分:2)

在创建对象B的实例之前,您需要一个A类实例(因为B是A的内部类)。 试试这段代码:

Foo foo = new Foo();
A a = new A();
B b = a.new B();
foo.bar(b);

答案 2 :(得分:0)

在您的代码中,B隐含了对A的引用,因此您需要一个Athis方法A,在new A()的上下文之外的A如果在您的应用程序中BI的命名空间中是A而没有实际使用{{1}之间的隐式引用1}}和B,您应该声明内部类A

static

现在以下内容应该有效:

public class A {
  //stuff
  public static class B implements I {}
}

public interface I {}

public class Foo {
  int bar(I i) {}
}

答案 3 :(得分:0)

是的,但是如果在grails服务中定义了实现接口的内部类。

在这种情况下,我们将如何实例化?

相关问题