Constructors in Java

  • Constructor is a special method whose name is same as that of class name.
  • Constructor should not have any return type, not even void.
  • Constructor will be invoked by the JVM automatically whenever you create the object.

The constructor is a block or code which similar to a method that is called when the instance of an object is created. It is useful for memory management. It provides data for the objects. In other words, it constructs values, which is why it is known as a constructor.


Example 1:


  • Constructor will be used to initialize instance variable of the class with a different set of values, but it's not necessary to initialise it.

  • When you are not writing any constructor inside the class then the default constructor will inserted by the JVM automatically,[at compile time].[If the class is public then the constructor will automatically be public, if it is default, then it will have default access specifier.]

  • When you write any constructor, then default constructor will not be inserted by the JVM.

  • You cannot specify the return type for the constructor, but if you do specify, then it will be treated as a normal method.

  • You can call the constructor with following ways:

    • A a=new A();
    • new A();
    • super(); // this point is covered in later chapters
    • this(); // this point is covered in later chapters
    • class.forName(“com.jbk.A”).newInstance(); // this point is covered in later chapters
  • Constructor can be overloaded i.e. you can write other constructors by changing the arguments.

  • You cannot write two constructors with the same number of parameters and same kind of types.

  • Constructors cannot be overridden.

  • Any access specifiers can be applied to constructors, if private is applied to constructor, then we cannot create an object outside of class.

  • If somebody says, if they want to create class, no one should instantiate it. Then you can say that the constructor must be private.

  • Mostly private constructors are used in singleton design pattern.

  • What is the use of constructors? You can say that if some code needs to be executed at object creation, then we can write that code in constructor. Generally. It's for initialization of global variable.

Let’s say there is a use case, client want to send sms and email so we can design class as below (without constructor).

Now we can observe here client need to send greeting message every time in each method So we need to reduce efforts of a client by using constructor.
See the below industrial example:

Example 2: Industrial Example


Here we initialize variables through constructors, we are not forcing to initialise, and therefore, we specified the default constructor as well. Different clients can now act differently, just consider the main method to be different for different clients.