Name: dbT83986 Date: 01/26/99 Consider this code: public class Outer implements Cloneable { int i = 5; Inner inner1 = new Inner(); class Inner implements Cloneable { public String toString() { return Integer.toString( i ); } } public Object clone() { try { Outer clone = (Outer) super.clone(); clone.inner1 = (Inner) inner1.clone(); return clone; } catch ( CloneNotSupportedException e ) { throw new Error( "CloneNotSupported: " + e.getMessage() ); } } public static void main( String[] args ) { Outer outer1 = new Outer(); Outer outer2 = (Outer) outer1.clone(); outer1.i = 8; System.out.println( outer1.inner1 + " " + outer2.inner1 ); } } When outer1 is cloned, its clone (outer2) has a new instance of Inner for its inner1 field, but this new instance is still considered to be enclosed by outer1. There is no easy way of making it part of outer2 instead since outer2 has to construct inner1 itself in order to enclose it. Any workarounds (e.g. below) require Inner cloning to be done manually, and this cloning has to be updated for changes to Inner fields. This gets very complicated if Inner is a subclass with an inheritance hierarchy!! I don't have any recommendations, but I feel this situation could be improved. Basically, I think some way is needed of reattaching a clone of an inner class to a different enclosing class. (Review ID: 34066) ======================================================================
|