Assign a subclass of a Generic class to a super class of this class

后端 未结 5 2109
心在旅途
心在旅途 2020-12-11 19:58

I have couple of supplied interfaces

public interface Finder,T extends Item> {
    public S find(S s, int a);
}

public interf         


        
5条回答
  •  借酒劲吻你
    2020-12-11 20:14

    The problem is that obviously Stack is not S extends Stack. Java is strongly typed and won't let you do such things.

    You can either cast to Stack, in which case you will still get a warning about unchecked conversion. This means this conversion is unsafe.

    public class SimpleFinder, T extends Item> implements Finder {
    
        @Override
        public S find(S s, int a) {
            Stack stack = s.getCopy();
            return (S) stack;
        }
    
    }
    

    or simply use Stack instead of S extends Stack, which is my recommendation:

    public class SimpleFinder implements Finder, T> {
    
        @Override
        public Stack find(Stack s, int a) {
            Stack stack = s.getCopy();
            return stack;
        }
    
    }
    

提交回复
热议问题