继承类在另一个继承类中

时间:2015-11-01 19:05:49

标签: java inheritance

我在Java中有继承问题。我会用军队的例子: 我有一个班级基地:

public class Soldier {
    Squad squad;

    public Soldier(Squad _squad) {
        squad = _squad;
    }
    //and some methods, that use squad 
}

我有:

public class Archer extends Soldier {
    public Archer(ArcherSquad _squad) {
        super(_squad);
    }
    //some new methods, some override 
}

public class Warrior extends Soldier {
    public Warrior(WarriorSquad _squad) {
        super(_squad);
    }
    //some new methods, some override 
}

我的小队看起来像:

Squad;
ArcherSquad extends Squad(some new methods);
WarriorSquad extends Squad(some new methods);

现在我想从ArcherSquad访问Archer中的方法。如何在不经纪的情况下更改代码?

1 个答案:

答案 0 :(得分:1)

您可以将对小队的引用移至ArcherSquad

public abstract class Soldier {
    // force subclass supply some squad
    protected abstract Squad getSquad();
    public void someMethod() {
        Squad squad = getSquad();
        // do something with it.
    }
}

public class Archer extends Soldier {
    private ArcherSquad archerSquad;
    public Archer(ArcherSquad _squad) {
        archerSquad = _squad;
    }
    @Override
    protected Squad getSquad() {
        return archerSquad;
    }
    ...
}

或者您可以将Soldier转换为通用类

public class Soldier<T extends Squad> {
    protected T squad;

    public Soldier(T _squad) {
        this.squad = _squad;
    }

    public void someMethod() {
        Squad squad = this.squad;
        // do something with it.
    }
}

public class Archer extends Soldier<ArcherSquad> {

    public Archer(ArcherSquad _squad) {
        super(_squad);
    }

    public void someMethodUsingArcherSquad() {
        ArcherSquad as = squad;
    }
    // some new methods, some override
}