簡體   English   中英

如何編寫一個引用類的構造函數,該類指向Java中的對象?

[英]How to write a constructor that takes a reference to a class, which points to an object in Java?

編寫另一個引用GeometricObject的構造函數是什么意思,它指向一個對象而不是null?

以及如何將這個對象初始化為參數對象的獨立副本?

以下代碼是GeometricObject類。

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;
  }

基本上,這意味着您的構造函數將使用同一類的另一個對象,並使用其值實例化一個新對象。

public GeometricObject(final GeometricObject other){
    this.color = other.color;
    this.filled = other.filled;
    //copy other member variables
}

然后,如果您有一個對象,則可以這樣創建它的副本:

final GeometricObject geometricObject = new GeometricObject();
//do stuff to geometricObject, give values to variables, etc
final GeometricObject copy = new GeometricObject(geometricObject);

所以你應該像這樣創建你的構造函數

public GeometricObject(GeometricObject original){
    if (original != null) {
        this.color = original.color;
        ... other variables ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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