Parametrized Constructor & Constructor Overloading in Java


Parameterized constructors
The parameterized constructors are the constructors having a specific number of arguments to be passed. The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.

Example :
      When we create the object like this Student s = new Student ( “Joes” , 15 ) then the new keyword invokes the Parameterized constructor with int and string parameters public Student( String n , String a ) after object creation.

Constructor overloading
       Constructors are special methods named after the class and without a return type, and are used to construct objects. Constructors, like methods, can take input parameters. Constructors are used to initialize objects. Constructor overloading in Java means to more than one constructor in an instance class.

This Java program demonstrates the concept of constructor overloading in a class. Constructor overloading is a technique in Java where a class can have multiple constructors with different parameters. In this program, the Box class has three constructors:

  • A default constructor with no parameters. This constructor initializes the instance variables length and breadth to 2 and 5, respectively.
  • A parameterized constructor with two parameters x and y. This constructor sets the instance variables length and breadth to the values of the parameters x and y, respectively.
  • A constructor with a single parameter x. This constructor sets both the length and breadth instance variables to the value of the parameter x

The area method calculates the area of the box using the length and breadth instance variables and returns the result.

In the main method, three objects of the Box class are created using the different constructors: o, o1, and o2. The area method is then called on each of these objects to calculate the area of the box.

Source Code

//Parameterized Constructor & Constructor Overloading
class Box
{
    float length,breadth;
    public Box(){  //Default
        length=2;
        breadth=5;
    }
    public  Box(float x,float y) //Parameterized
    {
        length=x;
        breadth=y;
    }
    Box(float x)
    {
        length=breadth=x;
    }
    float area()
    {
        return  length*breadth;
    }
}
public class constructor_overloading {
    public static void main(String args[]) {
        Box o =new Box();
        System.out.println("Area : "+o.area() );
 
        Box o1 =new Box(3,6);
        System.out.println("Area : "+o1.area() );
 
        Box o2 =new Box(3);
        System.out.println("Area : "+o2.area() );
    }
}
 

Output

Area : 10.0
Area : 18.0
Area : 9.0
To download raw file Click Here

Basic Programs