Create a copy of another rectangle (it is passed in the parameters):

public class Rectangle { private int left, top, width, height; Rectangle p; public Rectangle(int left, int top, int width, int height) { this.left = left; this.top = top; this.width = width; this.height = height; } public Rectangle(Rectangle p) { p.top = this.top; p.left = this.left; p.width = this.width; p.height = this.height; } } 

Why are parameters passed from main class variables? Do they not remain empty?

  • My question is rather the opposite. How to create a copy of the constructor? - hellog888
  • one
    What is a "copy triangle"? Maybe you meant a "diving triangle", that is, one that can fly a little bit? - Vlad from Moscow
  • one
    Some very strange copy constructor. In it, at least, it is necessary to swap what is to the left of the = sign with what is to the right of it. - post_zeew
  • What can copy the constructor? I see that he is strange :) - hellog888
  • one
    @HelloGoogle and why do you need to write a copy? And you understand that with this approach you risk going into endless recursion, because the copy will have its own copy, etc. and one awkward movement will result in an infinite number of Rectangle ? - Regent

2 answers 2

The way to clone an object you want to implement will look like this:

 public class Rectangle { private int left, top, width, height; public Rectangle(int left, int top, int width, int height) { this.left = left; this.top = top; this.width = width; this.height = height; } public Rectangle(Rectangle p) { this(p.left, p.top, p.width, p.height); } } 

Here a Rectangle(Rectangle p) object is passed to the Rectangle p constructor Rectangle(Rectangle p) , with the data of which the Rectangle(int left, int top, int width, int height) constructor is called Rectangle(int left, int top, int width, int height) .

    In this case, the java.lang.Object.clone() method can help. To use it the class should look like this:

     public class Rectangle implements Cloneable { private int left, top, width, height; public Rectangle(int left, int top, int width, int height) { this.left = left; this.top = top; this.width = width; this.height = height; } @Override public Rectangle clone() throws CloneNotSupportedException { return (Rectangle) super.clone(); } } 

    Then, to get a copy, you just call the method:

      Rectangle r1 = new Rectangle(1, 2, 4, 5); Rectangle r2 = r1.clone();