Java Constructors



Constructors : Initializing an Class Object in Java Programming

  1. Objects contain there own copy of Instance Variables.
  2. It is very difficult to initialize each and every instance variable of each and every object of Class.
  3. Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor.
  4. A Constructor initializes an object as soon as object gets created.
  5. Constructor gets called automatically after creation of object and before completion of new Operator.

Some Rules of Using Constructor :

  1. Constructor Initializes an Object.
  2. Constructor cannot be called like methods.
  3. Constructors are called automatically as soon as object gets created.
  4. Constructor don’t have any return Type. (even Void)
  5. Constructor name is same as that of “Class Name“.
  6. Constructor can accept parameter.

Live Example : How Constructor Works ?

class Rectangle {
  int length;
  int breadth;

  Rectangle()
  {
  length  = 20;
  breadth = 10;
  }

}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle();

  System.out.println("Length of Rectangle : " + r1.length);
  System.out.println("Breadth of Rectangle : " + r1.breadth);

  }
}

Output :

C:Priteshjava>javac RectangleDemo.java

C:Priteshjava>java RectangleDemo
Length  of Rectangle : 20
Breadth of Rectangle : 10

Explanation :

  1. new Operator will create an object.
  2. As soon as Object gets created it will call Constructor-
Rectangle()   //This is Constructor
  {
  length  = 20;
  breadth = 10;
  }
  1. In the above Constructor Instance Variables of Object r1 gets their own values.
  2. Thus Constructor Initializes an Object as soon as after creation.
  3. It will print Values initialized by Constructor –
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);