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;
}
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);
so your should create your constructor like that
public GeometricObject(GeometricObject original){
if (original != null) {
this.color = original.color;
... other variables ...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.