【问题标题】:How to override a generic method如何覆盖泛型方法
【发布时间】:2014-09-04 09:21:31
【问题描述】:

通用方法:

public <T> void foo(T t);

所需的覆盖方法:

public void foo(MyType t);

实现这个的java语法是什么?

【问题讨论】:

  • T受类约束吗?如,是包含在一些通用class Example&lt;T&gt; { } 中的方法

标签: java generics overriding


【解决方案1】:

更好的设计是。

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

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

【讨论】:

    【解决方案2】:

    你可能想做这样的事情:

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

    这里也回答了类似的问题:Java generic method inheritance and override rules

    【讨论】:

    • 你明白这里的MyType 是泛型参数名,而不是现有类的名称吗?
    【解决方案3】:
    interface Base {
        public <T> void foo(T t);
    }
    
    class Derived implements Base {
        public <T> void foo(T t){
    
        }
    }
    

    【讨论】:

    • 你认为这与这里有关吗?
    • 可能他想在覆盖的方法中有具体的实现。
    • @Snehal Masne 当然他可以在里面放任何实现。
    • @reporter 不是很明显
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多