Java Clone(클래스 복제) 인스턴스 코드

2290 단어 JavaClone
스스로 한 번 이루었다.

public class A implements Cloneable {
public String str[];

A() {
str = new String[2];
}

public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.str = new String[2];
return o;
}
}

void run() throws Exception {
A a1 = new A(), a2 = new A();
a1.str[0] = "a"; a1.str[1] = "b";
a2 = (A) a1.clone();
a2.str[0] = "c"; a2.str[1] = "d";
System.out.println(a1.str[0] + " " + a2.str[0]);
}

결과:
a c
일.

public class A implements Cloneable {
 public String name;

 public Object clone() {
  A o = null;
  try {
   o = (A) super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return o;
 }
}

이.

public class A implements Cloneable {
 public String name[];

 public A(){
  name=new String[2];
 }

 public Object clone() {
  A o = null;
  try {
   o = (A) super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return o;
 }
}

삼.

public class A implements Cloneable {   
     public String name[];   
     public Vector<B> claB;   

     public A(){   
         name=new String[2];   
         claB=new Vector<B>();   
     }   

     public Object clone() {   
         A o = null;   
         try {   
             o = (A) super.clone();   
         } catch (CloneNotSupportedException e) {   
             e.printStackTrace();   
         }   
         o.name=new String[2];// clone   
         o.claB=new Vector<B>();// clone    
         for(int i=0;i<claB.size();i++){   
             B temp=(B)claB.get(i).clone();// Class B clone
             o.claB.add(temp);   
         }   
         return o;   
     }   
 }

좋은 웹페이지 즐겨찾기