Copy constructor using private attributes
- by Pedro Magueija
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?