Copy constructor using private attributes
        Posted  
        
            by Pedro Magueija
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Pedro Magueija
        
        
        
        Published on 2010-03-11T18:23:26Z
        Indexed on 
            2010/03/11
            18:24 UTC
        
        
        Read the original article
        Hit count: 380
        
Hello all,
My first question here so be gentle.
I would like arguments for the following code:
public class Example {
    private String name;
    private int age;
    ...
    // copy constructor here
    public Example(Example e) {
        this.name = e.name; // accessing a private attribute of an instance
        this.age = e.age;
    }
    ...
}
I believe this breaks the modularity of the instance passed to the copy construct. This is what I believe to be correct:
public class Example {
    private String name;
    private int age;
    ...
    // copy constructor here
    public Example(Example e) {
        this.setName(e.getName());
        this.setAge(e.getAge());
    }
    ...
}
A friend has exposed a valid point of view, saying that in the copy construct we should create the object as fast as possible. And adding getter/setter methods would result in unnecessary overhead.
I stand on a crossroad. Can you shed some light?
© Stack Overflow or respective owner