开发者

Passing an inner class which implements an interface

Say I have the f开发者_Python百科ollowing:

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

public interface I {}

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

Now why does Java give me a build error of 'not applicable for type...' when I try to pass an instance of B to Foo.bar() inside the body of class A?

Is the inner class not considered a proper implementation of I because it is contained inside a top-level class?

Cheers, Dave.


You need a Instance of class A, before you can create a instance of object B (because B is a inner class of A). Try this code:

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


I suspect you may have two different I interfaces. Make sure you import the same ones in both files.

This is the exact error you get (from Eclipse) if you accidentally use two different interfaces with the same name.

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

For reference, this compiles fine for me:

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.
    }
}


In your code, B has an inplicit reference to A, so you need an A (the this inside a method of A, of a new A() outside the context of A) If in your application B is an I in the namespace of A without actually using the implicit reference between B and A, you should declare the inner class static:

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

public interface I {}

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

Now the following should work:

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


Yeah that's fine , but if the inner class which implement an interface is defined within grails service.

In that case how we will instantiate ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜