有 Java 编程相关的问题?

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

java传递实现接口的内部类

假设我有以下几点:

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

public interface I {}

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

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

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

干杯,戴夫


共 (4) 个答案

  1. # 1 楼答案

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

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

  2. # 2 楼答案

    在你的代码中,B有一个对A的不合法引用,所以你需要一个A(在A的方法中的this,在A的上下文之外的new A(),如果在你的应用程序中BA的命名空间中的I,而不是实际使用^{},您应该声明内部类static

    public class A {
      //stuff
      public static class B implements I {}
    }
    
    public interface I {}
    
    public class Foo {
      int bar(I i) {}
    }
    

    现在,以下措施应该可以奏效:

    Foo foo = new Foo();
    B b = new A.B();
    foo.bar(b);
    
  3. # 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.
        }
    }
    
  4. # 4 楼答案

    在创建对象B的实例之前,需要类a的实例(因为B是a的内部类)。 请尝试以下代码:

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