How Constructor in JAVA works? Learn with a simple example


  • Special method to initialize the object
  • When object of the class is created, constructor is called
  • Can be used to set initial value of attribute in object
  • Constructor is public
  • But in java we can create public, private, protected constructor
  • Private constructor : within a class


public class ConstructorDemo {

    int x;

    private ConstructorDemo()




    public static void main (String[] args){

        ConstructorDemo obj = new ConstructorDemo();

        System.out.println(“x: “+obj.x);



Next Example:

public class ConstructorDemo {

  int x;  // Class attribute is created

  // class constructor for the ConstructorDemo class is created

  public ConstructorDemo() {

    x = 5;  // Initialization of  value for the class attribute x


  public static void main(String[] args) {

    ConstructorDemo Obj = new ConstructorDemo(); //object of class ConstructorDemo  is created  which calls the constructor

    System.out.println(Obj.x); // Print the value of x as output




  • Default Constructor
  • No argument constructor
  • Parameterized Constructor
Facebook Comments

Comments are closed, but trackbacks and pingbacks are open.