0

Following code is from Apache Http Client.

HttpClientBuilder.java

public class HttpClientBuilder {

    public static HttpClientBuilder create() {
        return new HttpClientBuilder();
    }

    protected HttpClientBuilder() {
        super();
    }
}

Here, what is the purpose of creating a static method to get an instance? Why not a public constructor? Why call super() in the constructor?

s1n7ax
  • 2,750
  • 6
  • 24
  • 53
  • Note to only ask ONE question per question. ... that call to super() is just "bad style". The compiler inserts that call anyway into the compiled class file. It is simply good practice to not write it down unless needed in the java files. – GhostCat Nov 04 '20 at 08:19
  • And also for experienced members: remember to do research prior posting. Remember that almost anything about java has been asked here before, and (often extensively) been answered. – GhostCat Nov 04 '20 at 08:21

1 Answers1

1

If the code that wants a new instance of HttpClientBuilder creates the object itself via a constructor, then it will forever more create exactly that type of object, and it will lock in a certain set of parameters that it passes to the constructor.

The factory method create has more flexibility. As shown, it is returning a HttpClientBuilder anyway. But say something changes and and the authors of HttpClientBuilder want to, under certain circumstances, return a special new subclass of HttpClientBuilder. With the factory method, they can do that, and none of the client code will have to change or will even know the difference. That change can't be made without changing the client code in the case where the constructor is called directly. So the factory method generally has more flexibility for future modification by the class's authors than the constructor being called directly.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44