Constructor in Java | Different Types of Constructor?

 



In Java, a constructor is a special method that is called when an object of a class is created. It is used to initialize the state of an object. 

A constructor has the same name as the class and does not have a return type (not even void).



Java provides two types of constructors:


Default constructor (no-arg constructor) : A constructor that takes no arguments is called a default constructor. If a class does not have any constructor, the compiler provides a default constructor with no arguments.


Parameterized constructor : A constructor that takes some arguments is called a parameterized constructor. It is used to provide different values to the class properties at the time of object creation.



Here is an example of a class with a default constructor and a parameterized constructor:


class Student {
 
  private String name;
 
  private int rollNo;
 
  // default constructor
 
  Student() {
 
    this.name = "unknown";
 
    this.rollNo = 0;
 
  }
 
  // parameterized constructor
 
  Student(String name, int rollNo) {
 
    this.name = name;
 
    this.rollNo = rollNo;
 
  }
 
  public String getName() {
 
    return name;
 
  }
 
  public int getRollNo() {
 
    return rollNo;
 
  }
 
}



In this example, the class Student has two constructors: a default constructor Student() and a parameterized constructor Student(String name, int rollNo). 

The default constructor is used to initialize the properties name and rollNo with default values, while the parameterized constructor is used to initialize the properties with user-provided values at the time of object creation.



Here's an example of how to create objects of the class Student using both constructors:


// using default constructor
 
Student s1 = new Student();
 
System.out.println("Name: " + s1.getName() + ", Roll No: " + s1.getRollNo());
 
 
 
// using parameterized constructor
 
Student s2 = new Student("John Doe", 1);
 
System.out.println("Name: " + s2.getName() + ", Roll No: " + s2.getRollNo());



The output will be:


Name: unknown, Roll No: 0
 
Name: John Doe, Roll No: 1



As you can see, the first object is created using the default constructor and the second object is created using the parameterized constructor, providing different values for the properties.

Post a Comment

Post a Comment (0)

Previous Post Next Post