What are constructors in Java?

JavaServer Side ProgrammingProgramming

A constructor in Java is syntactically similar to methods. The difference is that the name of the constructor is same as the class name and it has no return type.

You need not call a constructor it is invoked implicitly at the time of instantiation. The main purpose of a constructor is to initialize the instance variables of a class.

Syntax

Following is the syntax of a constructor −

class ClassName {
   ClassName() {
   }
}

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

public class Test {
   int num;
   String data;
   Test(){
      num = 100;
      data = "sample";
   }
   public static void main(String args[]){
      Test obj = new Test();
      System.out.println(obj.num);
      System.out.println(obj.data);
   }
}

Output

100
sample
raja
Published on 05-Feb-2021 10:27:16
Advertisements