World's most popular travel blog for travel bloggers.

Parameterized Constructors in java

, , No Comments

Parameterized Constructors : Constructor Taking Parameters

In this article we are talking about constructor that will take parameter. Constructor taking parameter is called as “Parameterized Constructor“.

Parameterized Constructors :

  1. Constructor Can Take Value , Value is Called as – “Argument“.
  2. Argument can be of any type i.e Integer,Character,Array or any Object.
  3. Constructor can take any number of Argument.
  4. See following example – How Parameterized Constructor Works ? –

Example : Constructor Taking Parameter in Java Programming

class Rectangle {
  int length;
  int breadth;

  Rectangle(int len,int bre)
  length  = len;
  breadth = bre;

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

  Rectangle r1 = new Rectangle(20,10);

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


Output :

Length of Rectangle  : 20
Breadth of Rectangle : 10

Explanation :

Carefully observe above program – You will found something like this –
Rectangle r1 = new Rectangle(20,10);
This is Parameterized Constructor taking argument.These arguments are used for any purpose inside Constructor Body.
  • New Operator is used to Create Object.
  • We are passing Parameter to Constructor as 20,10.
  • These parameters are assigned to Instance Variables of the Class.
  • We can Write above statement like –
Rectangle(int length,int breadth)
  length  = length;
  breadth = breadth;
Rectangle(int length,int breadth)
  this.length  = length;
  this.breadth = breadth;
But if we use Parameter name same as Instance variable then compiler will recognize instance variable and Parameter but user or programmer may confuse. Thus we have used “this keyword” to specify that “Variable is Instance Variable of Object – r1“.


Post a Comment

Let us know your responses and feedback