Java方法覆盖而不在内部进行转换

时间:2013-11-04 21:55:19

标签: java inheritance interface override subclass

我有一个BasicFooBuilder类,它有一个buildFoo方法接受Foo并构建一些东西。但后来我想创建一个完整的构建器层次结构和我想要使用的更复杂的对象。目前我有这样的事情:

public interface Builder{
 public void buildFoo(BasicFoo foo);
}

public class BasicFooBuilder implements Builder{
 @override
 public void buildFoo(BasicFoo foo){
  //Do something
 }
}

public class FancyFooBuilder extends BasicFooBuilder{
 @override
 public void buildFoo(BasicFoo foo){
  ((FancyFoo)foo).doSomethingFancy();
 }
 //More stuff inherited from basic foo
}

public class FancierFooBuilder extends FancyFooBuilder{
 @override
 public void buildFoo(BasicFoo foo){
  ((FancierFoo)foo).doSomethingFancier();
 }
 //More stuff inherited from basic foo and fancy foo
}

类层次结构是这样的:

BasicFoo
  |
  FancyFoo
    |
    FancierFoo

所以问题是:

如果不在子类的覆盖方法中进行所有投射,我该如何做到?

1 个答案:

答案 0 :(得分:2)

您需要一个泛型类型参数,它基本上代表您自己构建的类。你不能仅限于一个班级,但你可以近距离接触。

public interface Builder<T extends BasicFoo> {
 public void buildFoo(T foo);
}

public class BasicFooBuilder<T extends BasicFoo> implements Builder<T> {
 @Override
 public void buildFoo(BasicFoo foo){
  //Do something
 }
}

public class FancyFooBuilder<T extends FancyFoo> extends BasicFooBuilder<T> {
 @Override
 public void buildFoo(T foo){
  foo.doSomethingFancy();
 }
 //More stuff inherited from basic foo
}

public class FancierFooBuilder<T extends FancierFoo> extends FancyFooBuilder<T> {
 @Override
 public void buildFoo(T foo){
  foo.doSomethingFancier();
 }
 //More stuff inherited from basic foo and fancy foo
}