DEV Community

Sakthi S
Sakthi S

Posted on

What is Constructor in java?

Constructor

  • In Java, a constructor is a block of codes similar to the method. It is called when an Object of the class is created.

  • It is a special type of method which is used to initialize the object.

Rule of Constructor

There are two rules defined for the constructor.

  • The Constructor has the same name as the class.

  • A Constructor must have no explicit return type.

  • The constructor is called automatically every time you make an object.

Syntax

class Classname{
    Classname(){
        // constructor body
    }
}
Enter fullscreen mode Exit fullscreen mode

Example

class Student {

    // Constructor
    public Student() {
       System.out.println("Constructor");
    }

    public static void main(String[] args) {
        System.out.println("Method");

        Student s1 = new Student();

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)