Monday, July 16, 2018

what is the code for cloning an object in java?

class Human implements Cloneable {
    int age;
    long salary;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class CloningExe {
    public static void main(String args[]) throws CloneNotSupportedException {
        Human h1 = new Human();
        h1.age = 21;
        h1.salary = 1200;
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        Human h2 = (Human) h1.clone();
        System.out.println("-----------------------");
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
    }
}
Output:
h1 age: 21, h1 salary: 1200
-------------------------------
h1 age: 21, h1 salary: 1200
h2 age: 21, h2 salary: 1200

2nd Approach:
class Human implements Cloneable {
    int age;
    long salary;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class CloningExe {
    public static void main(String args[]) throws CloneNotSupportedException {
        Human h1 = new Human();
        h1.age = 21;
        h1.salary = 1200;
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        Human h2 = (Human) h1.clone();
        h2.salary = 1300;
        System.out.println("-----------------------");
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
    }
}
Output:
h1 age: 21, h1 salary: 1200
------------------------------
h1 age: 21, h1 salary: 1200
h2 age: 21, h2 salary: 1300

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...