Java generics with class and nested static interface

后端 未结 2 1502
终归单人心
终归单人心 2020-12-09 20:32

I want to use a generic class inside a nested static interface. My objective is to do something like this:

public class MyClass{
    private MyInter         


        
2条回答
  •  醉梦人生
    2020-12-09 21:19

    It's not redundant. With a static interface:

    MyClass.MyInterface myInstance;
    

    and with a non-static innter class (an interface is always static):

    MyClass.MyInterface myInstance;
    

    A more real world example:

    Map map = ...;
    for (Map.Entry entry : map.entrySet()) {
        ...
    }
    

    The static approach has the advantage that you can import the nested type, and still specify the type parameters:

    class ClassWithAReallyLongName {
        static interface Entry {
        }
    }
    

    and

    import my.package.ClassWithAReallyLongName.Entry;
    
    class Foo {
        Entry bar;
    }
    

    though one should use that idiom with caution as to not confuse the reader.

提交回复
热议问题