Java - 扩展整个类层次结构

时间:2016-05-01 09:34:17

标签: java inheritance abstract-class multiple-inheritance

我有一个类层次结构:

abstract class BaseThing
{
    public abstract void doSomething();
}

class Thing1 extends BaseThing
{
    @Override
    public void doSomething()
    {
        doSomethingWithThing1();
    }
}

class Thing2 extends BaseThing
{
    @Override
    public void doSomething()
    {
        doSomethingWithThing2();
    }
}

// A dozen more classes that extend the BaseThing class. 

我需要创建整个树的扩展版本。 Java中没有多重继承,因此我将其创建为:

interface BaseThingExt
{
   public void doSomethingElse();
}

class Thing1Ext extends Thing1 implements BaseThingExt
{
    @Override
    public void doSomethingElse()
    {
        doSomethingElseWithThing1();
    }
}

//   All Thing.. classes are extended by ThingExt... classes

现在的问题。 我可以在哪里为所有ThingExt类添加一些公共字段?我不能将它们放在基接口中,因为它们会变成final static。我不能使BaseThingExt成为抽象类,因为Java不支持多重继承。我无法相信唯一的解决方案是在所有ThingExt类中复制它们十几次!

编辑:请注意,所有ThingExt类都应该扩展它们的Thing类而不仅仅是BaseThing类,因为每个派生类都有一些细节。所以@Hamdi Douss的答案是行不通的。

2 个答案:

答案 0 :(得分:7)

通常的技巧是使用组合而不是继承:

interface BaseThingExt
{
   public void doSomethingElse();
}

class ConcreteImplementation implements BaseThing, BaseThingExt {

    private final BaseThing thingDelegate;
    private final BaseThingExt extDelegate;

    public ConcreteImplementation(BaseThing thing, BaseThingExt ext) {
        this.thingDelegate = thing;
        this.extDelegate = ext;
    }


    @Override
    public void doSomething() {
        thingDelegate.doSomething();
    }

    @Override
    public void doSomethingElse() {
        extDelegate.doSomethingElse();
    }
}

答案 1 :(得分:3)

我建议添加一个超类AbstractBaseThingExt

abstract class AbstractBaseThingExt implements BaseThingExt
{
    private Object commonField;
    public Object getCommonField(){}
    public Object setCommonField(Object commonField){}
}

class ThingExt extends AbstractBaseThingExt
{
    public ThingExt(BaseThing base) {
        this.base = base;
    }

    public void doSomething()
    {
        this.base.doSomething();
    }
}

ThingExt类应在适当时将实现委托给base