DEV Community

Keerthiga P
Keerthiga P

Posted on

Constructor in Java

What is Constructor?
A constructor in Java is a special method used to initialize objects when they are created.

  • A constructor must have the exact same name as the class.

  • A constructor does not return any value, not even void

Types of Constructor

Default Constructor
A default constructor is a constructor with no parameters.
Example:

public class Student{
    String name;
    int age;
    // Default Constructor
    public Student(){
        System.out.println("Default constructor"); 
    }
    public static void main(String[] args){
        Student myStudent = new Student();
        myStudent.name = "keerthi";
        myStudent.age = 23;
        System.out.println(myStudent.name);
        System.out.println(myStudent.age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Parameterized Constructor:
A parameterized constructor takes values (parameters) to initialize the object.

Example:

public class Student {
  String name;
  int age;
  //constructor
  public Student(String Name, int Age){
      name = Name;
      age = Age;
  }
  public static void main(String args[]) {
    Student myStudent = new Student("keerthi", 23);
    System.out.println(myStudent.name);
    System.out.println(myStudent.age);
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Constructor Overloading
Constructor overloading means having multiple constructors in the same class with different parameter lists.

Example:

public class Student {
  String name;
  int age;
  //constructor overloading
  public Student(String Name, int Age){
      name = Name;
      age = Age;
  }
  public Student(){
      System.out.println("Constructor");
  }
  public static void main(String args[]) {
    Student myStudent = new Student("keerthi", 23);
    System.out.println(myStudent.name);
    System.out.println(myStudent.age);
    Student myStudent1 = new Student();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)