سؤال

Consider a class, hiding member from superclass. If implementing clone, then how to update both members correctly?

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 ... ?
   }
}
هل كانت مفيدة؟

المحلول

The standard way is to cast Child to Wrapper in order to access its hidden field.

Simple example:

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"
}

}

But why do you hide the field? This leads to programming errors and makes your code hard to read. I would suggest accessing the field with getters and setters. In fact, i suggest declaring abstract getters and setters in Wrapper in order to force subclasses to provide a corresponding field.

Best regards,

sam

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top