java - Java中是否可以从外部对象访问隐藏字段?

标签 java inheritance superclass member-hiding

考虑一个类,向父类(super class)隐藏成员。如果实现克隆,那么如何正确更新两个成员?

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,以强制子类提供相应的字段。

最诚挚的问候,

萨姆

关于java - Java中是否可以从外部对象访问隐藏字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18947496/

相关文章:

java - 取消覆盖 hashCode

java - 如何在 Payara Server 中禁用 HTTP OPTIONS 方法?

java - 类继承 : generic extends generic

Objective-C继承;从父类(super class)调用重写的方法?

Java:返回一个扩展带有参数的抽象类的对象

java - 如何覆盖在另一个已继承的类中赋值的变量

swift - 从父类(super class)访问子类函数

java - Android - 当我滚动时按钮会改变

java - Android Studio 在项目同步期间抛出异常

java - 如何使用 RxJava 逐个读取字符串数组成员并调用网络 API 获取第一个结果?