lundi 11 août 2014

Java copy-constructors

/**
  * Regular constructor.
  */
  public Galaxy(double aMass, String aName) {
    fMass = aMass;
    fName = aName;
  }

  /**
  * Copy constructor.
  */
  public Galaxy(Galaxy aGalaxy) {
    this(aGalaxy.getMass(), aGalaxy.getName());
    //no defensive copies are created here, since 
    //there are no mutable object fields (String is immutable)
  }

  /**
  * Alternative style for a copy constructor, using a static newInstance
  * method.
  */
  public static Galaxy newInstance(Galaxy aGalaxy) {
    return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
  }

(from http://www.javapractices.com/topic/TopicAction.do?Id=12)

Aucun commentaire:

Enregistrer un commentaire