LearnFrenzy
Sign in Take a free test

Access Modifiers and Packages · Access Modifiers Programs · Question 7

Immutable API response with private constructor in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Write an ApiResponse class with a private constructor and public static factories ok(data) and error(code, message); fields are private final with public getters, and print several responses.

Solution
Main.java
final class ApiResponse {
    private final int status;
    private final String data;
    private final String error;

    private ApiResponse(int status, String data, String error) { this.status = status; this.data = data; this.error = error; }

    public static ApiResponse ok(String data) { return new ApiResponse(200, data, null); }
    public static ApiResponse error(int status, String message) {
        if (status < 400 || status > 599) throw new IllegalArgumentException("not an error status: " + status);
        return new ApiResponse(status, null, message);
    }

    public boolean isOk() { return error == null; }
    public int status() { return status; }

    @Override public String toString() { return isOk() ? status + " " + data : status + " ERROR " + error; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(ApiResponse.ok("{\"user\":\"asha\"}"));
        System.out.println(ApiResponse.error(404, "user not found"));
        ApiResponse r = ApiResponse.error(503, "try later");
        System.out.println(r.isOk() + " " + r.status());
        try {
            ApiResponse.error(200, "oops");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output Verified by compiling and running

200 {"user":"asha"}
404 ERROR user not found
false 503
not an error status: 200

With the constructor private, only the two factories can create responses, so an "ok" with an error message cannot exist.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links