What are the rules to create a constructor in java?



A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Rules to be remembered

While defining the constructors you should keep the following points in mind.

  • A constructor does not have return type.

  • The name of the constructor is same as the name of the class.

  • A constructor cannot be abstract, final, static and Synchronized.

  • You can use the access specifiers public, protected & private with constructors.

Example

The following Java program demonstrates the creation of constructors.

 Live Demo

public class Student {
   public String name;
   public int age;
   public Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Output

Name of the Student: Raju
Age of the Student: 20

Advertisements