4. Constructors - mStylias/JavaTopics GitHub Wiki

Definition

The constructor of a class is a block of code that is always executed when a class object is created. It is often used to instantiate some (or all) of the private fields of the object

Basic constructor characteristics

  • Constructors must have the same name as the class within which it is defined
  • Constructors do not return any type
  • Constructors are called only once at the time of Object creation

Differences between a constructor and a method

Private constructor

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.

Use cases of private constructor

  • You can use it with static members-only classes.
  • You can use it with static utility or constant classes.
  • You can use it to serve singleton classes. (More of that in the design patterns topic)
  • You can use it to assign a name, for instance, creation by utilising factory methods.
  • You can use it to prevent subclassing.

Example implementation details

In the example we have created a Car class with a constructor that initializes the private fields of the corresponding object.
Also, there is the singleton class CarSettings, which uses a private constructor to instantiate an array of Strings representing the available car colors. Note that this array isn't actually used to check if the given color is contained in the available ones when creating a Car object. This is done to avoid unnecessary complexity for the showcase of the topic at hand.

Sources and more information

https://www.javatpoint.com/java-constructor
https://www.programiz.com/java-programming/constructors
https://www.geeksforgeeks.org/singleton-class-java/