在Java中,是否可以从外部对象访问隐藏字段?
考虑一个类,从超类中隐藏成员。如果实施克隆,那么如何正确更新两个成员在Java中,是否可以从外部对象访问隐藏字段?,java,inheritance,superclass,member-hiding,Java,Inheritance,Superclass,Member Hiding,考虑一个类,从超类中隐藏成员。如果实施克隆,那么如何正确更新两个成员 public class Wrapper implements Cloneable{ protected Collection core; protected Wrapper(Collection core) { this.core = core; } public Wrapper clone() { try { Wrapper ans = (Wrapper)
public class Wrapper implements Cloneable{
protected Collection core;
protected Wrapper(Collection core) {
this.core = core;
}
public Wrapper clone() {
try {
Wrapper ans = (Wrapper) super.clone();
ans.core = (Collection) core.getClass().newInstance();
for(Object o : core) {
ans.core.add( o.clone() );
}
return ans;
}
catch(CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
public class Child extend Wrapper {
protected ArrayList core; // for simpler access
public Child() {
super(new ArrayList());
this.core = (ArrayList) super.core;
}
public Child clone() {
Child ans = (Child) super.clone();
ans.core ... // how to update both core members?
// ans.super.core ... ?
// ans.this.core ... ?
}
}
标准方法是将
Child
强制转换为Wrapper
,以访问其隐藏字段
简单的例子:
public class Test {
public static class A {
protected String field = "I'm class A";
}
public static class B extends A {
protected String field = "I'm class B";
}
/**
* @param args
*/
public static void main(String[] args) {
B b = new B();
System.out.println(b.field); // prints "I'm class B"
System.out.println(((A) b).field); //prints "I'm class A"
}
}
但你为什么要隐藏这片土地?这会导致编程错误,并使代码难以阅读。我建议使用getter和setter访问字段。事实上,我建议在Wrapper
中声明抽象getter和setter,以便强制子类提供相应的字段
致以最良好的祝愿
萨姆