Last active
July 30, 2020 19:29
-
-
Save Audhil/16ebcfceeebef472f8ad6e562848ad6c to your computer and use it in GitHub Desktop.
Shallow Copy in Java - it doesn't support member classes, suitable for classes with only primitive types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ShallowCloneDemo { | |
public static void main(String[] args) throws CloneNotSupportedException { | |
Employee employee = new Employee("audhil", 31); | |
System.out.println(employee); | |
Employee employee2 = (Employee) employee.clone(); | |
System.out.println(employee2); | |
employee2.setAge(33); | |
employee2.setName("yup"); | |
System.out.println(employee2); | |
} | |
} | |
class Employee implements Cloneable { | |
String name; | |
int age; | |
public Employee(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
@Override | |
public String toString() { | |
return "Employee{" + | |
"name='" + name + '\'' + | |
", age=" + age + | |
'}'; | |
} | |
@Override | |
protected Object clone() throws CloneNotSupportedException { | |
return super.clone(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment