728x90
300x250

[Java] Deep Copy & Shallow Copy

 

1. 개념(Concept)


 

2. 소스 코드

 

class Account implements Cloneable{

        private String accnum;
        private int balance;

 

        public void setNum(String accnum)
        {
             this.accnum = accnum;  
        }

        public String getNum()
       {
            return this.accnum;
       }
 

         
       protected Object clone()
       {

 

               try{
                    Account account = (Account)super.clone();
                    return account;
               }
              catch(CloneNotSupportedException e)
              {
                   e.printStackTrace();
              }
              return null;
       } 

}

 

Source) Account.java

 

public class Program
{

      public static void deepcopy()
     {
              Account source = new Account();
              source.setNum("111");

 
             Account target = (Account)source.clone(); // clone()은 Overliding으로 구현.
  
              System.out.println( "소스원본:" + source.getNum() );
              System.out.println( "대상-깊은 복사:" + target.getNum() );

 

              System.out.println( "원본값 계좌번호 변경 333\n" );


              source.setNum("333");


              System.out.println( "소스원본:" + source.getNum() );
              System.out.println( "대상-깊은 복사:" + target.getNum() + "\n" );
       }


       public static void shallowcopy()
       {
              Account source = new Account();
           source.setNum("111");

 

              Account target = source;
  
              System.out.println( "소스원본:" + source.getNum() );
              System.out.println( "대상-얇은 복사:" + target.getNum() );

 

              System.out.println( "원본값 계좌번호 변경 333\n" );
              source.setNum("333");


              System.out.println( "소스원본:" + source.getNum() );
              System.out.println( "대상-얇은 복사:" + target.getNum() + "\n" );
       }

 

       public static void main(String args[])
       { 
              System.out.println("--- 1.깊은 복사------------------");
           deepcopy();

 

              System.out.println("--- 2.얇은 복사------------------");
            shallowcopy();
       }

}

 

 

 

Main Source) Program.java

 

3. 동작 결과

 

 


이해가 되었으면 합니다.^^

 

[첨부(Attachment)]

Sample-copy.zip

 

반응형

+ Recent posts