Home > Blockchain >  Inheritance for 2 shared class via interface in Java?
Inheritance for 2 shared class via interface in Java?

Time:04-28

In our Java (Spring Boot) app, we have a base request class as shown below:

@Data
public class BaseRequest {
    @NotNull
    private UUID uuid;
}

There are 2 request extending from this base class for Create and Update as shown below:

@Data
public class CreateRequest extends BaseRequest {

    @NotEmpty
    private String apiKey;

    @NotEmpty
    private String locationId;    
}
@Data
public class UpdateRequest extends BaseRequest {

    private String apiKey;

    private String locationId;    
}

The only difference between these 2 classes are mandatory fields (it is required in CreateRequest, but not mandatory in UpdateRequest.

Here is the method that uses these 2 requests:

private void setRequest(SaveRequest request) {
    IntegrationRequest integrationRequest = new IntegrationRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}

As the fields are not same (required / non required), I have to overload this method. But I tried to use a single setRequest method by passing another base class extending the current one and inheriting these 2 requests, but it does not work due to the some unshared fields. I also think to use interface, but I am really confused which approach I should use to solve this problem.

private void setRequest(UpdateRequest request) {
    IntegrationRequest integrationRequest = new IntegrationRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}

So, any idea to use just a single setRequest method by passing a shared or base class/interface?

CodePudding user response:

You could do something like this:

public interface Request {
    String getApiKey();
    String getLocationId();
}

@Data
public class CreateRequest extends BaseRequest implements Request {
    @NotEmpty
    private String apiKey;
    @NotEmpty
    private String locationId;
}

@Data
public class UpdateRequest extends BaseRequest implements Request {
    private String apiKey;
    private String locationId;
}

private void setRequest(Request request) {
    CreateRequest integrationRequest = new CreateRequest();
    integrationRequest.setApiKey(request.getApiKey());
    integrationRequest.setLocationId(request.getLocationId());

    // code omitted
}
  • Related