Constructor in java

The constructor is like a method which is used to initialize the state of an object, at the time of object creation by using the new keyword. There is some rule to add the constructor in your Java class.

Rules of constructor in java

  • Constructor name should be same as class names.
  • Does not have the return type.
  • Optional arguments.
  • Can overload.
  • Can’t to override.

Types of constructor

constructor in java
  • Default constructor.
  • Parameterized constructor.

Default constructor

When the programmer didn’t add the any kind of constructor, Java compiler automatically adds the default constructor at the time of compilation, To perform the instance variable initialization process. It’s initialize the default values to the instance variables.

Parameterized constructor

Parameterized constructor is completely differs from the default constructor. The default constructor does not have the any arguments, but the parameterized constructor has the at least one parameter. And parameterized constructor added by the developer. If a developer adds the any constructor, the Java compiler does not add the default constructor at the time of compilation.

package com.samplecoder.constructor;

public class ConstructorExample {
	private int id;
	private String name;

	// Java compiler adds this default constructor at the time of compilation. This is how the default constructor looks like. For example, I have added here
	ConstructorExample(){ = 0; = null;
	//Parameterized Constructor
	ConstructorExample(int id, String name){ = id; = name;