Java Constructors:

  • Constructors are special member features whose task is to initialize the objects of its class.
  • It is treated as a unique member characteristic because its name is similar to the class name.
  • Java constructors are invoked while their objects are created.
  • It is called such due to the fact, it constructs the value, i.e., offer information for the object, i.e., they may be used to initialize objects.
  • Each class has a constructor when we don’t explicitly claim a constructor for any java class the compiler creates a default constructor for that class which does no longer have any return type.
  • The constructor in Java can not be abstract, static, very last or synchronized and these modifiers aren’t allowed for the constructor.

 

Characteristics of Java Constructors:

 

  • An interface can’t have the constructor.
  • Constructors can’t be private.
  • Abstract, static, final can’t be constructor .
  • Constructors cannot return a value.
  • Constructors does not have a return type; no longer even void.
  • Constructors are routinely called while an object is created.

 

There are two types of constructors:

  1. Default constructor (no-arg constructor).
  2. Parameterized constructor.

Syntax:

 

1.  Default constructor (no-arg constructor):

  • A constructor does not have parameter’s is known as default constructor and no-arg constructor.

Example:

In this example, we are creating the no argument constructor in the Bike_Java class. It will be invoked at the time of object creation.

Output:

 

2.  Parameterized constructor:

  • A constructor having an argument list with it’s data type is known as a parameterized constructor.

Example:

In this example, we are creating the constructor in the Dog_Java class and passing the arguments to the constructor.

Output :

 

Note: If there is no constructor defined in a class, then compiler automatically creates a default constructor.