【发布时间】:2011-01-26 12:29:39
【问题描述】:
我在这里的第一个问题,所以要温柔。
我想要以下代码的参数:
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;
}
...
}
我相信这会破坏传递给复制构造函数的实例的模块化。 这是我认为是正确的:
public class Example {
private String name;
private int age;
...
// copy constructor here
public Example(Example e) {
this.setName(e.getName());
this.setAge(e.getAge());
}
...
}
一位朋友公开了一个有效的观点,说在复制构造中我们应该尽可能快地创建对象。添加 getter/setter 方法会导致不必要的开销。
我站在十字路口。你能解释一下吗?
【问题讨论】:
-
第一个问题很好。
标签: constructor attributes copy private