在类中实现多个接口

时间:2017-12-31 17:35:46

标签: java design-patterns

我有两个界面,界面i1和界面i2。它们都有不同的方法。 class c1扩展接口i1和接口i2 我正在使用依赖注入,并希望注入c1依赖项。 另外作为一个很好的编程实践,我们也应该编写接口代码。但是如果我使用i1声明一个引用变量,那么我就不能使用i2方法,反之亦然。

此外,我希望i1和i2是独立的接口,因为i1也是由其他类实现的,而且这些类不需要i2方法。

解决此问题的最佳方法是什么?

例如:

public interface Tree {
    public int findMin();
    public int findMax();
}

public interface IBalancedTree {
    public int rightRotation();
}

class NormalTree extends Tree {
    public int findMin(){
        // implementing find min
    }
    public int findMax(){
        // implementing find max
    }
}

class BalancedTree extends Tree, IBalancedTree {

    public int findMin(){
        // implementing find min
    }

    public int findMax(){
        // implementing find max
    }

    public int rightRotation(){
        // implementing right rotation
    }
}

class TreeManager {
    private Tree tree

    public TreeManager(Tree tree){
        this.tree=tree
    }

    //calling tree methods
    //even if i pass balanced tree object i can only call methods of tree class?.
}

1 个答案:

答案 0 :(得分:0)

您可以IBalancedTree延长Tree

public interface IBalancedTree extends Tree {
    public int rightRotation();
}

然后Tree变量可以使用Tree方法,IBalancedTree变量可以使用这两种方法。但我认为您也可以使用instanceof