Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active July 30, 2020 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/16ebcfceeebef472f8ad6e562848ad6c to your computer and use it in GitHub Desktop.
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
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