Constructor in Java | Java for Beginner | Java Language | Java learning Online.

Constructor

Java supports a special type of method, called a constructor , that enables an object to initialise itself when it is created.

Constructors have the same name as the class itself. Secondly , they do not specify a return type ,not even void. This this is because they attend the instant of class itself.

Lets See Creation and Calling of constructor through Example Given Below:-

Program:

Class Rectangle
{
   Int len,wid;
   Rectangle(int x,int y) // Creating Constructor
   {
      len=x;
      wid=y;
   }
   Int rectarea()
   {
      Return (len*wid);
   }
}

Class RectangleArea
{
   public static void main (String args[])
   {
      Rectangle rec=new Rectangle(15,10); // Calling of Constructor
      Int area=rec.rectarea();
      System.out.println(“Area=”+area);
   }
}



Output:

Area = 150


There are two types of Constructor :-

Default Constructor

A constructor that doesn't have parameter  is known as default constructor. 

Parametrised Constructor.

A constructor that have parameter is known as parameterized constructor. Means We have to Pass Parameter on runtime .

Lets See Both Through Example:-

Program: 

package javaexamples;
public class Rectangle
{
   double width , height;

   Rectangle() // default Constructor
   {
      System.out.println("\n------|A Rectangle having width and height|------\n");
   }

   Rectangle(double a, double b) // Parametrised Constructor.
   {
      width=a;
      height=b;
      System.out.println("Width of rectangle is :- \n "+ width);
      System.out.println("Height of rectangle is :- \n "+ height);

   }
   Double Area() // class method of area
   {
      return(width*height);
   }

   Double Perimeter() // class method of perimeter
   {
      return(2*(width+height));
   }

   public static void main(String[] args)
   {
      Rectangle obj = new Rectangle(); // calling default constructor
      Rectangle obj1 = new Rectangle(2,3); // calling parametrised constructor by passing parameters.

      System.out.println(" ");
      System.out.println("Area of Rectangle is:-\n"+obj1.Area());
      System.out.println("Perimeter of Rectangle is:-\n"+obj1.Perimeter());
   }
}


Output:

------| A rectangle having width and height |------

width of rectangle is:-
2.0

height of rectangle is:-
3.0

Area of rectangle is:-
6.0
Perimeter of rectangle is:-

10.0

Post a Comment

1 Comments