In: Computer Science
//Using Java language
Write a copy instructor for the following class. Be as efficient as possible.
import java.util.Random;
class Saw
{
   private int x;
   private Integer p;
//------------------------------------------
public Saw()
{
Random r = new Random();
       x = r.nextInt();
       p = new Integer(r.nextInt());
}
}
there is no concept called copy instructor java have only copy constructor.
A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument.
Saw.java
import java.util.Random;
public class Saw {
    private int x;
    private Integer p;
    //default (Normal) constructor
    public Saw(){
        Random r=new Random(); //Random is a class used for genrating random numbers
        x=r.nextInt();
        p=new Integer(r.nextInt());
    }
    //copy constructor
    //it will create a new obj by using  already existing obj
    public Saw(Saw saw){
        System.out.println("copy constructor called");
        x=saw.x;
        p=saw.p;
    }
    // Overriding the toString of Object class
    @Override
    public String toString() {
        return "Saw{" +
                "x=" + x +
                ", p=" + p +
                '}';
    }
}
Demo.java
import java.util.*;
public class SDemo {
    public static void main(String[] args) {
        // create a object1 for Saw class it will call a default constructor
        Saw object1=new Saw();
        //printing the values object1
        System.out.println(object1);
        //creating object2 by using object1
       // Following involves a copy constructor call
        Saw object2=new Saw(object1);
        //printing the values object2
        System.out.println(object2);
    }
}


"C:\Program Files Javaljdk1.8.0 121lbinljava.exe" Sawx-1358831207, p-1672367332) copy constructor called Sawx-1358831207, p-1672367332) Process finished with exit code O
"C:\Program Files Javaljdk1.8.0 121lbinljava.exe" Saw/XF-972383579, p= 11 7 3 6 4 4 7 51) copy constructor called Saw x-972383579, p-1173644751) Process finished with exit code O