In this lesson, you will learn
Note: This can be especially useful in scenarios where you want to initialize an object based on the properties of another object.
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());
}
}
Area of rect1: 20.0
Area of rect2: 20.0
Very good
You must be logged in to submit a review.