When you listen to the name Constructor, then what comes to your mind? Something like making or creating or building something. A constructor is also similar, it initializes an object immediately after its creation.
You can compare constructors with the methods. They are similar while differing in some aspects. Constructors don’t have any return type, unlike the methods. Also, the Constructor name must be the same as the class name, which is not possible when declaring methods.
public class ClassConstructor { //This is the constructor ClassConstructor() { } .... }
Rules for Writing Constructors
- The Constructor name should match with the name of the class in which it resides.
- In Java, the constructors can never be abstract, synchronized, static, and final.
- It should not have any return type and value.
- Constructors can have access modifiers to restrict their usage and for maintaining security.
Note: Even though you don’t use any constructor, JVM will construct a default constructor for your program during the time of compilation.
Types of Constructors in Java
In general, there are three types of constructors:
- Default Constructor
- No-Argument Constructor
- Parameterized Constructor
Let’s understand each one of them in brief.
Default Constructor
If a programmer does not or forget to implement the constructor inside the class, the Java compiler creates a default constructor in your code. Even though you will not see it in your source code, but during the compilation, it will be there. The body remains empty for the default constructor.
A default constructor looks like this:
public class ClassConstructor { //This is a default constructor ClassConstructor() { } .... }
No-Argument Constructor
As the name suggests, the constructors with no arguments are called no-argument constructors. The signature matched with the default constructor, but unlike default constructors, the body can contain code.
Example:
class Constructor { Constructor() { System.out.println("No-Argument Constructor called"); } }
Parameterized Constructor
Constructors with parameters or arguments fall under the category of the parameterized constructor. You can pass multiple arguments. If you want to initialize the class fields with default values, then use a parameterized constructor.
Example:
class Constructor { // data members of the class. String name; // Parameterized Constructor Constructor (String name) { this.name = name; } }
Note: programmers can make many parameters with the same name but different parameters.