Interfaces in java are used for polymorphism. The key point is that interfaces are only definitions not implementations. These declarations are also called method signatures as they declares the name, return-type and parameters of the method.
In your code FirstInterface
only declares a method which doesn't return anything. On the other hand SecondInterface
declares a method which returns an object of type FirstInterface
. But as I said, these are only declarations. These interfaces are implemented by Classes where we define their body.
I think nothing is better than a code snippet. So consider this example:
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;
}
}
Here MyInterface
and MyInterface2 are 2 interfaces. First one declares 3 methods which return nothing, integer and String respectively. Second interface declares method which returns object of type MyInterface
.
MyInterface
is implemented by 2 classes namely A
and B
. Both of them assign definitions to the methods as per their needs.
MyInterface2 is implemented by Class C
, which creates an reference myInterface
of type MyInterface
. Because MyInterface
was implemented by classes A
and B
, it can point to object of either of them. In the code above we made an object from class A
and associate it with myInterface
. Finally we return it as specified by the method signature. This is similar to what happening in your code. :)