CloneMain.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package samples.technology.reference;
  2. //ʲôÊÇÓ°×Óclone
  3. class UnCloneA {
  4. private int i;
  5. public UnCloneA(int ii) {
  6. i = ii;
  7. }
  8. public void doublevalue() {
  9. i = i * 2;
  10. }
  11. public String toString() {
  12. return Integer.toString(i);
  13. }
  14. }
  15. class CloneB implements Cloneable{
  16. public int aInt;
  17. public UnCloneA unCA = new UnCloneA(111);
  18. public Object clone(){
  19. CloneB o = null;
  20. try{
  21. o = (CloneB)super.clone();
  22. }catch(CloneNotSupportedException e){
  23. e.printStackTrace();
  24. }
  25. return o;
  26. }
  27. }
  28. public class CloneMain {
  29. public static void main(String[] a){
  30. CloneB b1 = new CloneB();
  31. b1.aInt = 11;
  32. System.out.println("before clone,b1.aInt = "+ b1.aInt);
  33. System.out.println("before clone,b1.unCA = "+ b1.unCA);
  34. CloneB b2 = (CloneB)b1.clone();
  35. b2.aInt = 22;
  36. b2.unCA.doublevalue();
  37. System.out.println("=================================");
  38. System.out.println("after clone,b1.aInt = "+ b1.aInt);
  39. System.out.println("after clone,b1.unCA = "+ b1.unCA);
  40. System.out.println("=================================");
  41. System.out.println("after clone,b2.aInt = "+ b2.aInt);
  42. System.out.println("after clone,b2.unCA = "+ b2.unCA);
  43. }
  44. }