Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For java,how to make sure inner interface and outer interface have same generic type?

Version 1

public interface Outer<T>{
    public interface Inner<T>{
        T get();
        void set(T t);
    }
}

Although same generic type syntax ,these two type are totally independent.

Version 2

public interface Outer<T>{
    public interface Inner<V extends T>{
        V get();
        void set(V t);
    }
}

Got an error:"Cannot make a static reference to the non-static type T"

Version 3

public interface Outer<T>{
    public interface Inner{
       <T> T get();
       <T> void set(T m);
    }
}

Not sure whether this is what I want, but seems fine (no errors in eclipse), so I try to implement it:

public Test implements interface Outer.Inner {
       //no problem in these two
       <T> T get(){..};
       <T> void set(T m){...};

        //Errors come up here:
       Map<String,T> map;
       public Test(Map<String,T> map){
            this.map=map
       }

}

the error comes up: "T cannot be resolved to a type" in both

  1. declaration Map<String,T> map
  2. constructor argument public Test(Map<String,T> map){}

so,how can I solve this problem?

like image 614
Alex Luya Avatar asked Feb 16 '11 07:02

Alex Luya


1 Answers

Firstly, there is no way to do this, since the outer interface is nothing more than a "namespace" for the inner interface. They really have nothing else to do with each other.

This begs the question: why would you need to have such a control over things? If, in the class which implements the interface, it is decided that using the same type makes sense, then it will be so for that class. But another implementation could, and should be allowed to, choose otherwise. This is especially true since classes which implement Outer and those implementing Inner are not restricted to being nested with each other.

like image 141
Ken Wayne VanderLinde Avatar answered Oct 04 '22 13:10

Ken Wayne VanderLinde