从接口调用接口

Calling an interface from an interface

我正在处理一个有一些遗留代码的项目,我不确定某些接口如何相互交互。

有两个接口,看起来像这样:

public interface FirstInterface {
     void someFunction();
}

第二个调用 (?) 第一个:

public interface SecondInterface {
     FirstInterface fi();
}

我是 Java 的新手,我不明白这是某种形式的嵌套界面还是这里发生了其他事情。我也不确定 FirstInterface fi() 是否调用接口或创建该类型的方法,如果是这样,与 FirstInterface fi 之类的操作相比有什么优势?如果有帮助,这两个接口都在不同的包中。

如果我可以添加任何信息使这一点更清楚,请告诉我,谢谢!

需要实现接口。所以会有一个 class,比如 FirstClass,定义如下:

class FirstClass implements FirstInterface {
    public void someFunction() {
        System.out.println("Hello, world!");
    }
}

和另一个实现 SecondInterface 的 class。从语法中注意到方法 fi() returnsFirstInterface 的一个实例;它不调用它。事实上,你不能调用一个接口(或一个class):你只能调用方法。

要return一个FirstInterface的实例,fi()方法必须创建一个class的对象来实现它(比如FirstClass),并且return那个对象。作为练习,您可能想尝试编写 class SecondClass 及其 fi() 方法。

java 中的接口用于 多态性 。关键是 接口只是定义而不是实现 。这些声明也称为方法签名,因为它们声明了方法的名称、return-类型和参数。

在您的代码中 FirstInterface 只声明了一个方法,没有 return 任何东西。另一方面,SecondInterface 声明了一个 return 类型为 FirstInterface 的对象的方法。但正如我所说,这些只是声明。这些接口由我们定义其主体的 Classes 实现。 我认为没有什么比代码片段更好的了。所以考虑这个例子:

public interface MyInterface{
    void meathod1();
    int meathod2();
    String meathod3();
}

public interface MyInterface2{
    MyInterface meathod4();
}

public class Class A implements MyInterface{
    public void meathod1(){     
    } 

    public Integer meathod2(){
        return 0;       
    }

    public String meathod3(){       
        return "Apple";
    }
}

public class Class B implements MyInterface{
    public void meathod1(){     
    } 

    public Integer meathod2(){
        return 1;       
    }

    public String meathod3(){       
        return "Banana";
    }
}

public class Class C implements MyInterface2{
    public MyInterface meathod4(){
        MyInterface myInterface = new A();
        return myInterface;
    }
}

这里MyInterface和MyInterface2是2个接口。第一个声明了 3 个方法,分别是 return nothing、integer 和 String。第二个接口声明 returns 类型 MyInterface 对象的方法。

MyInterface 由 2 个 class 实现,即 AB。他们都根据需要为方法分配定义。

MyInterface2 由 Class C 实现,它创建了一个类型为 MyInterface 的引用 myInterface。因为 MyInterface 是由 classes AB 实现的,它可以指向其中任何一个的对象。在上面的代码中,我们从 class A 创建了一个对象并将其与 myInterface 相关联。最后我们 return 它按照方法签名指定。这类似于您的代码中发生的情况。 :)