Constructor in Java

A constructor referred to as a special type of method in java. The name of the constructor is the same as the class name. The constructor doesn’t have any return type. The objective of a constructor is to initialize the newly created object.
 
Constructor example:
class Student {
// this is constructor
Student () {
      }
//some code
}

Understanding Constructor :

Let’s discuss the concept of a constructor with an example.
In a class, there is a variable called name, and you need to initialize(or assign some value) at the time of creating an object. So, we use the constructor to do this operation.

 
class Student {
String name;
//constructor
Student() {
this.name = “PLMDeveloper”;
}
public static void main(String args[]) {
Student obj = new Student();
System.out.println(“Student name is: ” + name);
  }
}
 
Output:
PLMDeveloper
 
Types of Constructors
  1. Default constructor
  2. No-Arg constructor
  3. Parameterized constructor
 

Default Constructor

In a java class, if you don’t implement any constructor by default compiler, insert a constructor. This constructor is called a default constructor. The default constructor doesn’t have any code.
 

no-arg Constructor

If you implement any constructor without any arguments in your class, then it is called a no-arg constructor. This constructor looks similar to the default constructor, but in the no-arg constructor, you can implement the code.

Parameterized Constructor:

A constructor with parameters known as parameterized constructor. If you want to initialize the variables in your constructors dynamically with your values, you have to use a parameterized constructor.
 
 
class Student {
String sName;
//constructor
Student(String name) {
this.sName =name ;
}
public static void main(String args[]) {
Student obj = new Student(“Developer”);
System.out.println(“Student name is: ” + name);
  }
}
 
Output:
Developer
 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top