0

What does it mean to write another constructor that takes a reference to GeometricObject, which points to an object rather than null?

And how can I Initialize this object to be an independent copy of the parameter object?

The following code is the GeometricObject class.

public class GeometricObject {
public String color = "white";
public double area = 0;
public double perimeter = 0;

  public boolean filled;

  /** Construct a default geometric object */
  public GeometricObject() {
  }

  public GeometricObject(String color, boolean filled){
      this.color = color;
      this.filled = filled;
  }


  /** Return color */
  public String getColor() {
    return color;
  }

  /** Return area */
  public double getArea(){
      return area;
  }

  /** Return object */
  public GeometricObject copy() {
      return null;
  }


  /** Return perimeter */
  public double getPerimeter(){
      return perimeter;
  }

  /** Set a new color */
  public void setColor(String color) {
    this.color = color;
  }

  /** Return filled. Since filled is boolean,
   *  the get method is named isFilled */
  public boolean isFilled() {
    return filled;
  }

  /** Set a new filled */
  public void setFilled(boolean filled) {
    this.filled = filled;
  }



  @Override
  public String toString() {
    return "\ncolor: " + color + " and filled: " + filled;
  }
Tobb
  • 11,850
  • 6
  • 52
  • 77
Ben.W
  • 65
  • 2
  • 3
  • 10
  • [Why do we need copy constructor and when should we use copy constructor in java](https://stackoverflow.com/q/29362169/669576) – 001 Oct 23 '17 at 14:41

2 Answers2

0

It basically means that your constructor takes in another object of the same class, and instantiates a new object using its values.

public GeometricObject(final GeometricObject other){
    this.color = other.color;
    this.filled = other.filled;
    //copy other member variables
}

Then, if you have an object, you can create a copy of it like this:

final GeometricObject geometricObject = new GeometricObject();
//do stuff to geometricObject, give values to variables, etc
final GeometricObject copy = new GeometricObject(geometricObject);
Tobb
  • 11,850
  • 6
  • 52
  • 77
0

so your should create your constructor like that

public GeometricObject(GeometricObject original){
    if (original != null) {
        this.color = original.color;
        ... other variables ...
    }
}
marco
  • 671
  • 6
  • 22