我正在做一个有一些遗留代码的项目,我不知道某些接口是如何相互交互的。
有两个接口,如下所示:
public interface FirstInterface {
void someFunction();
}
第二个叫(?)第一项:
public interface SecondInterface {
FirstInterface fi();
}
我对Java很陌生,我不明白这是某种形式的嵌套接口,还是这里发生的其他事情。我也不确定FirstInterface fi()
是调用接口还是创建这种类型的方法,如果是的话,与FirstInterface fi
这样的操作相比,有什么优势呢?如果有帮助,这两个接口都在不同的包中。
如果我能添加任何信息使这更清楚,请让我知道,谢谢!
发布于 2020-07-21 13:56:17
java中的接口用于多态性。关键是接口只是定义,而不是实现。这些声明也称为方法签名,因为它们声明了方法的名称、返回类型和参数。
在您的代码中,FirstInterface
只声明一个不返回任何内容的方法。另一方面,SecondInterface
声明了一个返回FirstInterface
类型对象的方法。但正如我所说,这些只是声明而已。这些接口由类实现,我们在这些类中定义它们的主体。我认为没有什么比代码片段更好了。因此,请考虑以下示例:
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是两个接口。第一个方法声明3个方法,它们分别不返回任何内容、整数和字符串。第二个接口声明返回MyInterface
类型对象的方法。
MyInterface
由两个类( A
和B
)实现。这两种方法都根据自己的需要为方法分配定义。
MyInterface2由类C
实现,它创建一个类型为MyInterface
的引用myInterface
。因为MyInterface
是由A
和B
类实现的,所以它可以指向其中任何一个的对象。在上面的代码中,我们从类A
创建了一个对象,并将其与myInterface
相关联。最后,我们按照方法签名指定的方式返回它。这与代码中发生的情况类似。:)
发布于 2020-07-21 13:27:32
接口需要实现。所以会有一个类,比如FirstClass,定义了这样的东西:
class FirstClass implements FirstInterface {
public void someFunction() {
System.out.println("Hello, world!");
}
}
以及实现SecondInterface的另一个类。从语法中注意,fi()
方法返回FirstInterface
的一个实例;它不调用它。实际上,您不能调用接口(或类):只能调用方法。
要返回FirstInterface
的实例,fi()
方法必须创建实现它的类的对象(例如FirstClass),并返回该对象。作为练习,您可能需要尝试编写类SecondClass
及其fi()
方法。
https://stackoverflow.com/questions/63015431
复制相似问题