开发者

Cloning objects of inner classes

开发者_StackOverflow中文版I have written a class A such as following

class A <E> {  // class A has objects of E

    int x;

    private B<T> next // a object of inner class

    class B<T> { 
        // an inner class having objects of type T

        T[] elements = (T[]) Object[x];
        // has other stuff including many objects  
    }

 public A<E> func ( B<E> val ){
  Here I want to clone the value of val so that I can do different operations on other   
 }

The problem comes that I wish to write B<E> Temp = B<E>Value.clone() where Value is defined in the code.

but it says that clone is not visible.

What should I do to make it so....

Thanks a lot...


clone() is protected so you just need to redefine in B to do whatever you need.


Here an example to the answers from Peter (not tested, may need some syntax checks):

class A <E> {  // class A has objects of E

    int x;

    private B<T> next // a object of inner class

    class B<T> implements Cloneable {
        public B<T> clone() {
           try {
              B<T> klon = (B<T>) super.clone();
              // TODO: maybe clone the array too?
              return klon;
           }
           catch(CloneNotSupportedException) {
              // should not occur
              throw new Error("programmer is stupid");
           }
        }
        // an inner class having objects of type T

        T[] elements = (T[]) Object[x];
        // has other stuff including many objects  
    }

 public A<E> func ( B<E> val ){
     B<E> clone = val.clone();
     // more code
 }


It's better to not use clone() but to implement a copy constructor on B:

 class B extends A { 
    // an inner class having objects of type 
    List<String> strings = ArrayList<String>();

    public B(B that) {
       super(that); // call the superclass's copy constructor
       this.strings = new ArrayList<String>();
       this.strings.add(that.strings);
    }

    // ...
}

then call

public C func ( B val ){
   B clone = new B(val);
}

(removed the generics stuff to limit demonstration on the copy constructor itself)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜