首页 > 解决方案 > 如何使用基本接口引用调用扩展接口函数?

问题描述

对不起,如果我的问题没有任何意义。我会在这里尝试解释一下。假设我有一个这样的基本接口:

public interface SimpleInterface {
    public void function1(); 
}

扩展接口如下:

public interface ExtendedInterface extends SimpleInterface{
    public void function2();
}

可以说我有一个实现的类ExtendedInterface

public class Implementation implements ExtendedInterface {

    @Override
    public void function1() {
        System.out.println("function1");
    }

    @Override
    public void function2() {
        System.out.println("function2");
    }
}

现在,function2()当我得到一个用类SimpleInterface实例化的基接口 ()时,有什么方法可以调用,如下所示:Implementation

SimpleInterface simpleInterface = new Implementation();

我知道它违背了接口的目的,但它可以让我免于进行大量代码更改。

标签: javaoopinterface

解决方案


基本上,您必须强制转换为ExtendedInterface

SimpleInterface simpleInterface = new Implementation();
ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();

当然,如果simpleInterface引用的对象实际上没有实现,则强制转换将失败ExtendedInterface。这样做的必要性绝对是一种代码味道 - 它可能是您可用的最佳选择,但至少值得考虑替代方案。


推荐阅读