使用泛型实现从具有公共父类的类继承



我有一个由许多其他类继承的类。对于每一个,我都需要一个子类,我在其中重写一个方法。但是这个方法实际上是在基类中定义的,所以如果我可以使用泛型并使用单个实现就太好了。像这样:

public class MyBase
{
void myMethod()
{
doSomething();
}
}
public class A extends MyBase
{
}   
public class B extends MyBase
{
}
public class MyCommonSubclass <T extends MyBase> extends T //Can't do it like this
{
@Override
void myMethod()
{
doSomethingElse():
}
}

是否有一个简单的方法来实现?(我不这么认为,但我还是要问一下,以防我错了。)(是的,这个问题是糟糕设计的结果,但现在我不得不忍受它。)

No。不能扩展自由变量类型,接口不能扩展类。

最接近的是实现一种Trait (Java中不直接支持)。

// this interface reverse the type parameter restriction
public interface RequiredToRestrictTraitToHaveNameMethod {
String name();
}
public static class MyBase implements RequiredToRestrictTraitToHaveNameMethod {
public String name() {
return this.getClass().getCanonicalName();
}
}
// a normal common class/trait
public interface TraitFoo {
default void foo() {
System.out.printf("- FOO %s!%n", this.getClass().getCanonicalName());
}
}
// a special type restricted common class/trait
public interface TraitBar extends RequiredToRestrictTraitToHaveNameMethod {
default void bar() {
System.out.printf("- BAR %s!%n", name()); // here is your T type
}
}
public static class MySuper extends MyBase implements TraitBar {
}
public static class MySuperBad extends MyBase implements TraitBar {
// here is your override
@Override
public String name() {
return "OverridedNameOfMyParent";
}
}
public static void main(String[] args) {
new MySuper().bar();
new MySuperBad().bar();
}

与输出

- BAR com.computermind.sandbox.observer.Test.MySuper!
- BAR OverridedNameOfMyParent!

使用接口和默认实现,你可以实现类似的行为,但是,不知道你到底想做什么(为此,你将不得不在SO中创建另一个请求),我不能给你一个完整的例子。

最新更新