javaconstructordomain-object

Why do we need this special type of constructor?


public MyConstructor(MyConstructor mc){
   this.setId(mc.getId());
   this.setName(mc.getName());
}

Here why do we need to set the value in constructor by getting its getter method. Is there any special purpose behind this ?


Solution

  • As already pointed out in the other answers, this sort of constructor mainly is intended for cloning objects, and is sometimes referred to as copy constructor

    As Joshua Bloch suggests in his Book "Effective Java", Item 11, such a constructor should usually be preferred over implementing the clone() method, because the clone() method has some issues (see the book or corresponding stackoverflow questions for details).

    There is no striking reason to implement it exactly like that - thus, one does not really need it in exactly this form. As mentioned in the comments, one could (most likely) alternatively write it as

    public MyConstructor(MyConstructor mc){
        this.id = mc.getId();
        this.name = mc.getName();
    }
    

    or

    public MyConstructor(MyConstructor mc){
        this.setId(mc.id);
        this.setName(mc.name);
    }
    

    or

    public MyConstructor(MyConstructor mc){
        this.id = mc.id;
        this.name = mc.name;
    }
    

    The author here chose to use the nested set(mc.get()) approach. It has the potential advantage that it solely relies on the interface that is defined in terms of get/set methods, and thus may be more robust against changes.

    One could argue about whether this is a good practice in general, but I think that for a copy constructor, it nicely and clearly states: "This object is initialized here, solely based on (and exactly like) the given object".


    Side note: Cloning an object and giving the clone the same ID most likely defeats the purpouse of an ID - but there might be cases where this is appropriate