Constructors

6.3 Constructors

A constructor is a member method that automatically initializes an object immediately upon creation. It has the same name as the class with no return type. Let’s defining a simple constructor of Rectangle class as shown here:
   public Rectangle()
   {
      length = 0.0;
      width  = 0.0;
   }
When we write following statment to create object constructor automatically invoked and Rectangle object automatically intiliaze with value 0;
  Rectangle rectangle1 = new Rectangle();
A constructor can have parameters, this version of constructor is called parameterized constructor. Following code segment define a parameterized constructor.
   public Rectangle(double l, double w)
   {
      length = l;
      width  = w;
   }
Paramterized constructor intializes object with given set of values when object is created, look at following statement :
  Rectangle rectangle2 = new Rectangle(3.5, 4.2);
A class can have multiple constructors, compiler differentiate on the basis of parameter passed. This is called overloading of constructor.
Here is complete example :
/**
 * A Rectangle class with constructors
 */
public class Rectangle
{
   private double length;
   private double width;

   /**
    * Constructor
    */
   public Rectangle()
   {
      length = 0.0;
      width  = 0.0;
   }

   /**
    * Overloaded constructor
    */
   public Rectangle(double l, double w)
   {
      length = l;
      width  = w;
   }

   /**
    * The set method accepts two arguments
    * which are stored in the length and width fields
    */
   public void set(double l, double w)
   {
      length = l;
      width  = w;
   }

   /**
    * The getArea method computes and returns the area
    */
   public double getArea()
   {
      return length * width;
   }

   /**
    * The getPerimeter method computes and returns the perimeter
    */
   public double getPerimeter()
   {
      return 2 * (length + width);
   }
}
(RectangleDemo. Java)
/**
 * This program tests Rectangle class
 */
public class RectangleDemo
{
   public static void main(String[] args)
   {
      // Create a Rectangle object with default values
      Rectangle rectangle1 = new Rectangle();

      System.out.println("Area of Rectangle is "
                         + rectangle1.getArea());
      System.out.println("Perimeter of Rectangle is "
                         + rectangle1.getPerimeter());

      // Create a Rectangle object with given set of values
      Rectangle rectangle2 = new Rectangle(3.5, 4.2);

      System.out.println("Area of Rectangle is "
                         + rectangle2.getArea());
      System.out.println("Perimeter of Rectangle is "
                         + rectangle2.getPerimeter());
   }
}
Output :
Area of Rectangle is 0.0
Perimeter of Rectangle is 0.0
Area of Rectangle is 14.7
Perimeter of Rectangle is 15.4

No comments:

Post a Comment

Pages