Advertisement

JAVA Constructor Overloading Program Using Object as Parameter

JAVA Constructor Overloading Program Using Object as Parameter

JAVA Constructor Overloading Program Using Object as Parameter

Generally, constructors are used to initialize class member variables. When we use multiple constructors in a class definition, then it is known as constructor overloading. We can use default constructors and parameterized constructors for the overloading. 

But, in this program, I am showing the use of the class's object as a parameter in the constructor. Here the class is Shape, so I am using the object s of the class Shape as the parameter of the last constructor.
When the constructor calls, the s4 object is created with the copy of the s3 object as a parameter. So, the display area method will return the same value for s3 and s4 objects.

class Shape //general class
{
    int side1, side2; //member variables
    Shape() //default constructor [no parameter]
    {
        side1=side2=0;
    }
    Shape(int x) //single parameterized constructor
    {
        side1=side2=x; //initialize with x
    }
    Shape(int x, int y) //double parameterized constructor
    {
        side1=x; side2=y; //initialize with x y
    }
    Shape(Shape s) //single parameterized constructor
    {
        side1=s.side1; //initialize with s object
        side2=s.side2;
    }
    void display_Area() //member method
    {
        System.out.println("Area of the shape ="+(side1*side2));
    }
}
public class MainShape //main class
{
    public static void main(String args[])
    {
        Shape s1 = new Shape(); //1st object create
        s1.display_Area(); //area=0
        Shape s2 = new Shape(5); //2nd object create
        s2.display_Area(); //area=25
        Shape s3 = new Shape(4,6); //3rd object create
        s3.display_Area(); //area=24
        Shape s4=new Shape(s3); //4th object
        s4.display_Area(); //area=24
    }
}

Output:-

Output of Java constructor overloading using object parameter


Post a Comment

0 Comments