Website For Developers

Constructor in Java



Syntax

constructor_name {
//constructor body
}

Example of constructor in Java

public class HelloWorld {

  HelloWorld() { //constructor
    System.out.println( "Object is created!" );
  }

  public static void main(String[] args) {
    HelloWorld obj1 = new HelloWorld();
    HelloWorld obj2 = new HelloWorld();
  }
}

Output

Object is created!
Object is created!


Working of above example


Parameterized Constructor in Java


Syntax

Syntax of Passing parameters to a constructor in Java is as following:

Class_name object_name = new Class_name (parameters);


Example of parameterized constructor in Java

public class PassingExample {

   PassingExample (int a, int b) {
     System.out.println(a+b);
   }

   public static void main(String[] args) {
     PassingExample obj1 = new PassingExample (10 , 20);
   }
}

Output

30