If you look in the books, they tell you that a constructor is there to enable you to instantiate a class. But the truth is, the constructor is there to restrict instantiation. If you have one constructor with
String int
as the parameter types, that tells users, “yes, you can instantiate this class but you must provide me with a String and an int.”
You can add more constraints to it, for example:-
You can read about requireNonNull
here. There are other ways to verify the contents of a String.
If you look in the
Java® Language Specification (this is one of the few parts easy to understand), you find that you can use the access modifier on the constructor to restrict instantiation a different way.