95e560c211e515aaeecea2ac266f14dd4e5a3a3b.svn-base 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package samples.technology.reference1;
  2. class UnCloneA implements Cloneable{
  3. private int i;
  4. public UnCloneA(int ii) {i = ii; }
  5. public void doublevalue() {i *= 2; }
  6. public String toString() {
  7. return Integer.toString(i);
  8. }
  9. public Object clone(){
  10. UnCloneA o = null;
  11. try{
  12. o = (UnCloneA)super.clone();
  13. }catch(CloneNotSupportedException e){
  14. e.printStackTrace();
  15. }
  16. return o;
  17. }
  18. }
  19. class CloneB implements Cloneable{
  20. public int aInt;
  21. public UnCloneA unCA = new UnCloneA(111);
  22. public Object clone(){
  23. CloneB o = null;
  24. try{
  25. o = (CloneB)super.clone();
  26. }catch(CloneNotSupportedException e){
  27. e.printStackTrace();
  28. }
  29. o.unCA = (UnCloneA)unCA.clone();
  30. return o;
  31. }
  32. }
  33. public class CloneMain {
  34. public static void main(String[] a){
  35. CloneB b1 = new CloneB();
  36. b1.aInt = 11;
  37. System.out.println("before clone,b1.aInt = "+ b1.aInt);
  38. System.out.println("before clone,b1.unCA = "+ b1.unCA);
  39. CloneB b2 = (CloneB)b1.clone();
  40. b2.aInt = 22;
  41. b2.unCA.doublevalue();
  42. System.out.println("=================================");
  43. System.out.println("after clone,b1.aInt = "+ b1.aInt);
  44. System.out.println("after clone,b1.unCA = "+ b1.unCA);
  45. System.out.println("=================================");
  46. System.out.println("after clone,b2.aInt = "+ b2.aInt);
  47. System.out.println("after clone,b2.unCA = "+ b2.unCA);
  48. }
  49. }
  50. /** RUN RESULT:
  51. before clone,b1.aInt = 11
  52. before clone,b1.unCA = 111
  53. =================================
  54. after clone,b1.aInt = 11
  55. after clone,b1.unCA = 111
  56. =================================
  57. after clone,b2.aInt = 22
  58. after clone,b2.unCA = 222
  59. */