How to override a generic method

回眸只為那壹抹淺笑 提交于 2019-12-04 02:50:37

问题


Generic method :

public <T> void foo(T t);

Desired overridden method :

public void foo(MyType t);

What is the java syntax to achieve this?


回答1:


A better design is.

interface Generic<T> {
    void foo(T t);
}

class Impl implements Generic<MyType> {
    @Override
    public void foo(MyType t) { }
}



回答2:


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




回答3:


interface Base {
    public <T> void foo(T t);
}

class Derived implements Base {
    public <T> void foo(T t){

    }
}


来源:https://stackoverflow.com/questions/25661730/how-to-override-a-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!