开发者

Java Generics use

public class A implements SomeInterface<B>{
    ...
    class B{
     ....
    }
 ....
}开发者_StackOverflow社区

Class B is declared in class A so when I write SomeInterface<B> would it work although B is declared only in A?


Something like that:

interface SomeInterface <T> {
    void doing (T t);
}

public class A implements SomeInterface <A.B> {
    public void doing (A.B ab) {}
    class B {}
}


No problem conceptually.


As far as syntax is concerned, B cannot be directly referenced outside A's body without import

http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.3

"The scope of a declaration of a member m declared in .. a class type C is the entire body of C"

So these are illegal

@Anno(M.class)  // illegal
class C implements X<M>  // illegal
      class M

However I think that is too restrictive; it could have been extended a little more. Consider

@Anno(C.class)  // legal
class C implements X<C>  // legal

that's because the scope of the top level class C is the entire "type declaration", which is bigger than mere "entire body". There is no reason why we couldn't extend M's scrope to be "the entire type declaration of C" as well.

See also Static inner classes need import for annotations

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜