Java,克隆具有访问限制的类
我有:Java,克隆具有访问限制的类,java,clone,encapsulation,Java,Clone,Encapsulation,我有: 类人员实现可克隆 personne类在其字段中使用address类 私有地址=未知地址 所以我想要的是有一个选项: 修改克隆人地址 以下是我的克隆方法: Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException cnse) { cnse.printStackTrace(System.err); } return o; } 但是原始Person类将无法访问 克
- 类人员实现可克隆
- 私有地址=未知地址李>
- 修改克隆人地址
以下是我的克隆方法:
Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException cnse) { cnse.printStackTrace(System.err); } return o; }
- 但是原始Person类将无法访问 克隆人类地址字段
@Override
public Personne clone()
{
Personne o;
try {
o = (Personne)super.clone();
o.adresse = null;
return o;
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
throw new RuntimeException();
}
}
// setter pour l adresse du Clone :
public void setAdresseClone(Adresse a){
this.clone().adresse = a;
}
请给我小费 试试这个:
public Personne clone()
{
Personne o;
try {
o = (Personne)super.clone();
o.adresse = null;//or just change it however you want here.
return o;
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
throw new RuntimeException();
}
}
请确保Personne的属性是不可变的,如果不是,则应在main clone()方法中分别为每个不可变的属性调用clone()方法。好的,伙计们,在帮助下我理解了。 重写clone()方法的可能性是使oputunity可以修改克隆类的字段。建议的解决方案是将类的address字段重置为NULL。 然后,我创建了一个setter,它提供了修改clone address字段的选项
@Override
public Personne clone()
{
Personne o;
try {
o = (Personne)super.clone();
o.adresse = null;
return o;
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
throw new RuntimeException();
}
}
// setter pour l adresse du Clone :
public void setAdresseClone(Adresse a){
this.clone().adresse = a;
}
也许克隆人在道德上是错误的?我的建议是让我们在英格兰进行克隆,在那里克隆是被授权的。为什么不重写clone()方法,并在调用clone()时修改地址呢?我将把它添加到主主题中,因为这里它在同一行中进行计算好的,看起来不错。但是告诉我:你是如何更改地址的访问权限的?@Vladimir我没有更改地址的访问权限它仍然是私有的,但是由于
clone()
方法也在Personne
类中,它可以访问私有属性Adrese
。是的!这正是我的问题。但是看看你的代码,我说你正在访问这个人的地址字段并覆盖它。但是由于它被修改了,它仍然可以被原始的Person类访问,如果你明白我的意思的话。如果我这样做,你认为这可能是一个解决方案吗?p.s.i.l在主主题中发表文章