2014-09-04 54 views
0

泛型方法:如何重写泛型方法

public <T> void foo(T t); 

希望重写的方法:

public void foo(MyType t); 

什么是Java语法来实现这一目标?

+0

T受T的约束吗?如在中,是一些通用'类中包含的方法示例 {}' – Upio 2014-09-04 09:35:54

回答

2

更好的设计是。

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

class Impl implements Generic<MyType> { 
    @Override 
    public void foo(MyType t) { } 
} 
0
interface Base { 
    public <T> void foo(T t); 
} 

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

    } 
} 
+0

您认为这里与此有关吗? – VinayVeluri 2014-09-04 09:29:06

+0

这是答案。你认为它错了吗? – talex 2014-09-04 09:30:50

+0

也许他想在overriden方法中具体实现。 – 2014-09-04 09:38:23

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

+0

你是否明白'MyType'这里是通用参数名称,不是现有类的名称? – talex 2014-09-04 09:41:33