Sunday, 4 March 2012

Copy Constructor


public class WithoutCopyConstructor {
 private int [] a;
 private int n; //length of the array
 public WithoutCopyConstructor(){
  this(10);   
 }
 public WithoutCopyConstructor(int size){
  n=size;
  a= new int[n];
 }
 public WithoutCopyConstructor(WithoutCopyConstructor t){
  this.n= t.n;
  this.a=t.a; 
 }
 public int [] getArray(){
   
  return a;
 }
 public void setArray(int [] b)
 {
  a=b; 
 }
 public void show(){
  String s="";
  for(int i=0; i<n; i++)
   s+="" + a[i];
  System.out.println(s);
 }

}

//////////////////
public class Driver {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  WithoutCopyConstructor wcc1 = new WithoutCopyConstructor(5);
  WithoutCopyConstructor wcc2 = wcc1;
  wcc1.show();
  wcc2.show();
  int [] t;
  t = wcc1.getArray();
  t[0]=1;
  wcc1.show();
  wcc2.show();
  WithoutCopyConstructor wcc3 = new WithoutCopyConstructor(wcc1);
  int []p = wcc3.getArray();
  p[0]=2;
  wcc1.show();
  wcc2.show();
  wcc3.show();
 
 }
}

No comments:

Post a Comment