快捷导航

java中关于类组合的一个问题

//一条线段包含两个端点  public class Point{    //点类   private int x, y;     public Point(int x, int y) {        this.x = x;        this.y = y;   }   public int GetX() {         return x;    }   public int GetY() {         return y;    }}class Line{   //线段类   private Point  p1,p2;     // 两端点   Line(Point a, Point b) {        p1 = new Point(a.GetX(),a.GetY());   //这里为什么不使用p1 = a; p2 = b;      p2 = new Point(b.GetX(),b.GetY());   }    public double Length() {        return Math.sqrt(Math.pow(p2.GetX()-p1.GetX(),2)                                  + Math.pow(p2.GetY()-p1.GetY(),2));    }}在上面的代码中:
p1 = new Point(a.GetX(),a.GetY());   p2 = new Point(b.GetX(),b.GetY()); //这里为什么不使用p1 = a; p2 = b;

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员1

p1=a的话,只要a改变了,Line里的p1也会改变,所以需要把Point里的值拿出来做深度拷贝,避免这种不可控现象
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP