elibraryportal Logo

Constructor in Java

→ Constructor is a special type of method also contains collection of statements that is used to initialize objects. When an object of a class is created. It can be used to set initial values for object attributes:.

Rules for creating constructor

  1. Constructor name must be the same as, the class name √
  2. No explicit return type √
  3. Access modifiers can be used in constructor declaration to control its access √
  4. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

→ There are two types of constructors in Java:

  1. Default constructor or no-arg constructor
  2. Parameterized constructor

1) Default Constructor in java

If you don't define a constructor in a class, then compiler automatic creates a Default Constructor for the class, it is also known as no arguments.

Example1 :

Output

Default constructor Example in java

Example2 :

Output

No Argument constructor Example in java

2) Parameterized Constructor in java

→ Constructor that have parameters is known as parameterized constructor.

Example1 :

Output

Parameterized Constructor Example in java

Constructor Overloading in Java

Constructor overloading is a technique, more than one constructor with different parameter list, and each constructor performs a different task .

Example1 :

Output

Parameterized Constructor Example in java