How to override a generic method

后端 未结 3 535
醉梦人生
醉梦人生 2021-01-17 00:05

Generic method :

public  void foo(T t);

Desired overridden method :

public void foo(MyType t);

W

相关标签:
3条回答
  • 2021-01-17 00:10

    A better design is.

    interface Generic<T> {
        void foo(T t);
    }
    
    class Impl implements Generic<MyType> {
        @Override
        public void foo(MyType t) { }
    }
    
    0 讨论(0)
  • 2021-01-17 00:17
    interface Base {
        public <T> void foo(T t);
    }
    
    class Derived implements Base {
        public <T> void foo(T t){
    
        }
    }
    
    0 讨论(0)
  • 2021-01-17 00:30

    You might want to do something like this :

    abstract class Parent {
    
        public abstract <T extends Object> void foo(T t);
    
    }
    
    public class Implementor extends Parent {
    
        @Override
        public <MyType> void foo(MyType t) {
    
        }
    }
    

    A similar question was answered here as well : Java generic method inheritance and override rules

    0 讨论(0)
提交回复
热议问题