我需要将我的复制构造函数设置为我的点和段类的深层复制,但我不确定我是否做对了。有人可以帮忙吗?
public class Segment implements SegmentInterface {
// two Points that hold endpoints of the segment
private Point p1;
private Point p2;
// Default constructor that will set the endpoints to new
// Points with values (0,0) and (4,4)
public Segment() {
//this(0, 0, 4, 4);
this.p1 = new Point(0, 0);
this.p2 = new Point(4, 4);
}
// Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
// and creates and sets the endpoints
public Segment(int x1, int y1, int x2, int y2) {
//this.p1 = new Point(x1, y1);
//this.p2 = new Point(x2, y2);
if(x1 != x2 && y1 != y2){
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
}
else{
throw new IllegalArgumentException("undefined");
}
}
// Parameterized constructor that accepts (Point p1, Point p2) and sets both
// the endpoints to a deep copy of the Points that are passed in.
public Segment(Point p1, Point p2) {
if(p1 != p2){
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
else{
throw new IllegalArgumentException("Points cannot have same values!");
}
}
// Copy constructor that accepts a Segment and initializes the data (of the
// new Segment being created) to be the same as the Segment that was
// received.
public Segment(Segment other) {
this.p1 = other.p1;
this.p2 = other.p2;
}
请考虑这不是整个代码!
My Point课程是:
public class Point implements PointInterface {
// hold the x-value and the y-value of the Point
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
// default constructor that will set the values to (0, 0)
public Point() {
this.x = 0;
this.y = 0;
}
// parameterized constructor that will receive 2 ints (first the x
// coordinate and then the y)
// and set the data variables to the values received.
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// A copy constructor that will receive a Point and then initializes the
// data
// Deep Copy
public Point(Point other) {
this.x = other.getX();
this.y = other.getY();
}
答案 0 :(得分:0)
几乎不错。将此构造函数用于段:
public Segment(Segment orig)
{
this(orig.p1, orig.p2);
}