Why does Retrofit use Interface instead of a normal java class?

Ahmed Ghrib :

In my Android, I am using Retrofit to implement an http client.
Retrofit uses interfaces to define the possible http operations.

userInterface.java

UserInterface.java
public interface UserInterface {
   // Retrofit callback
   @POST("login")
   Call<Integer> signin(@Body LoginActivity.UserInfo userInfo);
}

This UserInterface is then used by retrofit in the loginActivity.java:

loginActivity.java

// It makes sense. Retrofit will use the interface as a configuration file
UserInterface userInterface = ApiClient.getApiClient().create(UserInterface.class);

ApiClient.java

public static Retrofit getApiClient(){
   if (retrofit==null){
       retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();
   }
   return retrofit;
};

I understood everything about how Retrofit Client configuration and how it works. However, I couldn't see why userInterface is a java interface instead of a normal java class?
I know that in a nutshell this is what an interface is:

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

I have also understood the particular role of the interface with Retrofit:

You can see the interface as a configuration file, it holds info (method declaration , return type and params, annotations) about each endpoint (link a method name to url, GET or POST, parameters and parameter types, return value type , ... and more). the engine uses those info to serialize parameters (if needed), execute the request and deserialize the response (if needed).

However, I still cannot explain to myself the use of an interface instead of a normal java class?

Lino :

If you take a look at the source code of the Retrofit library, in particular the create() method of Retrofit.java class, you can see that they're using Java's Dynamic Proxy approach to create classes at runtime.

This mechanism requires an interface (or a list of interfaces) in order to create proxy classes that have particular behaviour. This explains why the use of an interface instead of normal java class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=359241&siteId=1