DEV Community

Cover image for Constructor in Java
Sasireka
Sasireka

Posted on

Constructor in Java

1) What is Constructor?

A constructor is a special method in Java used to initialize objects. It is automatically called when an object of a class is created.

  • Name: A constructor must have the same name as the class.

  • No Return Type: A constructor does not have a return type, not even void.

2) Types of Constructor

Default Constructor:

A default constructor is a constructor with no parameters.

The Java compiler makes a default constructor if we do not write any constructor in our program.

Example:

public class Student{

    String name;
    int age;

    // Default Constructor
    public Student(){

        System.out.println("Default constructor"); 

    }
    public static void main(String[] args){

        Student student1 = new Student();
        student1.name = "Sasireka";
        student1.age = 23;
        System.out.println(student1.name);
        System.out.println(student1.age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Parameterized Constructor:

A parameterized constructor is used to assign values to object variables when the object is created.

Example:

public class Student {
  String name;
  int age;

  //Parameterized constructor
  public Student(String Name, int Age){
      name = Name;
      age = Age;
  }

  public static void main(String args[]) {
    Student student1 = new Student("Sasireka", 23);
    System.out.println(student1.name);
    System.out.println(student1.age);
  }

}

Enter fullscreen mode Exit fullscreen mode

Output:

3) Constructor Overloading

Constructor overloading - A class have more than one constructor with different no of parameters or with different type of parameter.

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 student1 = new Student("Sasireka", 23);
    System.out.println(student1.name);
    System.out.println(student1.age);

    Student myStudent1 = new Student();

  }

}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)