javacloneabledate

Java deep copy difference between a String and Date object


How to create a deep copy for a date object, for example birthDate of a student? how will copying a date object different from Name or age?

Here is an example for cloning I got from net.

import java.util.Date;
public class Clone
{
    public static void main(String[] args)
    {
        Date d1 = new Date(90,10,5);
        Object d2=d1.clone();
        System.out.println("Original Date:" +d1.toString());
        System.out.println("Cloned Date:" +d2.toString());
    }
}

But is this a deep copying?

OUTPUT Original Date:Mon Jan 05 00:00:00 IST 2018 Cloned Date:Mon Jan 05 00:00:00 IST 2018 –

adding additional Info...

so how can I put the code inside my class ?

// insideCloneable class
/overriding clone() method to create a deep copy of an object. 
protected Object clone()throws CloneNotSupportedException{ 
        Employee employee = (Employee) super.clone();
        return employee;  
        }

//implementing  class - main method 
Employee employee1 = new Employee(01,"John","02-11-2017");
        Employee employee2 = null;
employee2=(Employee)employee1.clone();

Solution

  • Date original = new Date();
    Date copy = new Date(original.getTime());
    

    java 8+ new API

    Original link