簡體   English   中英

在java中初始化沒有new運算符的對象

[英]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類型。 我嘗試編譯並運行兩個版本的構造函數。 兩者都運作良好。 所以我很困惑哪一個會更好用,為什么,也有區別,因為在第一個我沒有使用新操作來初始化中心對象。

第二個構造函數使用原始center實例的防御副本 (由Point2D構造函數調用生成)以防止輸入實例的進一步突變(更改),這可能會非常混亂並產生錯誤

所以我很困惑哪一個會更好用,為什么

第二種方法更安全,因為你的Point2D類是可變的。 它使用更多的內存(以保持額外的防御性副本),但在真正的復雜項目中,這種設計實踐的優點多於缺點。

如果你可以使Point2D不可變,那么可以使用第一個構造函數。

第二個構造函數創建一個新的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM