user506710
user506710

Reputation:

Cloning objects of inner classes

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...

Upvotes: 0

Views: 2554

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114767

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)

Upvotes: 0

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

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
 }

Upvotes: 0

Peter Hull
Peter Hull

Reputation: 7067

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

Upvotes: 1

Related Questions