Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Passing Object as a Parameter to a Constructor

In this lesson, you will learn

  • Passing Object as a Parameter to Constructor
  • Examples

 

Passing an Object as a Parameter in a Constructor

  • In Java, passing an object as a parameter to a constructor is a common practice that allows for more complex data structures and interactions between objects.

 

Note: This can be especially useful in scenarios where you want to initialize an object based on the properties of another object.

 

Example 1: Passing Object as a Parameter to Constructor

package ch8.l5;

class Rectangle {
   double length;
   double width;

    // Constructor to initialize length and width
    public Rectangle(double l, double w) {
        length = l;
        width = w;
    }

    // Constructor that accepts a Rectangle object
    public Rectangle(Rectangle otherRectangle) {
        length = otherRectangle.length;
        width = otherRectangle.width;
    }

    // Method to calculate area
    public double calculateArea() {
        return length * width;
    }
}

public class PassObInConstructor {
    public static void main(String[] args) {
        // Create a Rectangle object
        Rectangle rect1 = new Rectangle(5.0, 4.0);

        // Create another Rectangle object by passing rect1
        Rectangle rect2 = new Rectangle(rect1);

        // Display the area of both rectangles
        System.out.println("Area of rect1: " + rect1.calculateArea());
        System.out.println("Area of rect2: " + rect2.calculateArea());
    }
}

Output

Area of rect1: 20.0
Area of rect2: 20.0

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

05/04/2025

Very good

 

 

Submit a Review