如何使用基本接口参考调用扩展接口功能?

时间:2018-07-31 16:49:31

标签: java oop interface

很抱歉,我的问题没有任何意义。我将在这里尝试解释。假设我有一个像这样的基本接口:

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();

我知道它违反了接口的目的,但是它将使我免于进行大量代码更改。

4 个答案:

答案 0 :(得分:3)

基本上,您必须转换为ExtendedInterface

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

当然,如果simpleInterface所引用的对象不是实际上实现ExtendedInterface,则转换将失败。这样做绝对是一种代码味道-它可能是您可以使用的最佳选择,但至少值得考虑其他选择。

答案 1 :(得分:1)

首先,您应该检查对象实例是否实际上是Implementation类的实现,因为可能有多个类正在实现此Interface。

您可以按照以下步骤进行操作:

//Somewhere in the code 
SimpleInterface simpleInterface = new Implementation();

//Now with the variable you can check it as below
if(simpleInterface instanceof Implementation)
Implementation implemenation = (Implementation)simpleInterface;
implemenation.function2();

答案 2 :(得分:1)

可以调用的方法受左侧类型(SimpleInterface)的限制,并且由于SimpleInterface没有方法function2(),因此无法调用function2()simpleInterface对象上。

为此,请进行如下强制转换(具体是downcast):

ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();

或更简洁地说:

((ExtendedInterface) simpleInterface).function2()

答案 3 :(得分:0)

如其他人的建议那样,这是一个选择,但这并不是完全的证明。我们可以在这里使用反射

    Method[] methods = simpleInterface.getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals("function2"))

        try {
                method.invoke(simpleInterface);
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

使用上面的代码将确保在具有此方法的对象的引用上调用function2方法

相关问题