[英]Initializing an object without new operator in java
這兩個構造函數之間有什么區別。
Circle (Point2D center, double radius) {
this.center = center;
this.radius = radius;
}
Circle (Point2D center, double radius) {
this.center = new Point2D(center.getX(), center.getY());
this.radius = radius;
}
繼承看Point2D課程。 這兩個版本的構造函數都運行得很好。 我只是感到困惑的是什么區別。
class Point2D {
double x;
double y;
Point2D () {
x = 0;
y = 0;
}
Point2D (double x, double y) {
this.x = x;
this.y = y;
}
void setX (double x) {
this.x = x;
}
void setY (double y) {
this.y = y;
}
void setXY (double x, double y) {
this.x = x;
this.y = y;
}
double getX () {
return x;
}
double getY () {
return y;
}
double distance (Point2D p) {
double x1 = p.getX();
double y1 = p.getY();
return Math.sqrt(Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2));
}
double distance (double x, double y) {
return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2));
}
}
Circle類還有2個場中心和半徑。 center是Point2D類型,radius是double類型。 我嘗試編譯並運行兩個版本的構造函數。 兩者都運作良好。 所以我很困惑哪一個會更好用,為什么,也有區別,因為在第一個我沒有使用新操作來初始化中心對象。
第二個構造函數創建一個新的Point實例 - this.center = new Point2D(center.getX(), center.getY());
而不是保持對傳遞給它的實例的引用。 這意味着如果稍后修改了傳遞的center
,則更改不會影響Circle
實例。
第二個構造函數通常更安全,因為它有一個真正的私有Point
實例作為Circle
的中心,而第一個構造函數與構造函數的調用者共享center
。
您可以看到與此代碼的區別:
Point2D point = new Point2D(10.0, 20.0);
Circle circle = new Circle (point, 4.0);
point.setX (5.0);
System.out.println(circle); // assuming you override toString to display the properties
// of the Circle
如果使用第一個構造函數,執行此代碼后,您的圓將具有(5.0,20.0)的中心,而如果使用第二個構造函數,則圓的中心將為(10.0,20.0);
Point2D
不是不可變的,即具有可在構造點之后改變的屬性。
Circle
的第一個構造函數只使用Point2D
對象 - 現在調用者可以更改也會影響圓的點對象。
Circle
的第二個構造函數生成Point2D
對象的副本 。 如果圓圈使點對象保持私有,則無法從外部更改。
this.center = center
,你使用center
對象的參數。
this.center = new Point2D(center.getX(), center.getY())
,用參數center
值創建Point2D
新對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.