Java constructor example



Yet Another Constructor Example : More Detailed Example (Java Programming)

class Rectangle {
  int length;
  int breadth;

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

  void setDiamentions()
  {
  length  = 40;
  breadth = 20;
  }

}

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);

  r1.setDiamentions();

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

  }
}

Output :

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

Explanation :

  1. After the Creation of Object , Instance Variables have their own values inside.
  2. As soon as we call method , values are re-initialized.