class
Clone class example
This is an example of how to create a clone class of a class. We have created Employee class to get its clone class, as shown below:
- The class
Employeehas two String fields and a Double field and getters and setters for the fields. - It overrides the
clone()method of Object, where it creates a newEmployeeobject and sets to its fields the values of the fields of the object. - It also overrides the
toString()method of Object, where it returns the name of the class the instance belongs to and its fields values. - We create a new
Employeeobject and get its clone object. Then we change a field’s value in the original object. This change does not pass to the clone object.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
public class CloneClass {
public static void main(String[] args) {
Employee e1 = new Employee("Mark", "Adams");
e1.setValue(40000.0);
Employee e2 = (Employee) e1.clone();
e1.setLName("Smith");
System.out.println(e1);
System.out.println(e2);
}
}
class Employee {
private String lname;
private String fname;
private Double value;
public Employee(String lastName, String firstName) {
this.lname = lastName;
this.fname = firstName;
}
public String getLName() {
return this.lname;
}
public void setLName(String lastName) {
this.lname = lastName;
}
public String getFName() {
return this.fname;
}
public void setFName(String firstName) {
this.fname = firstName;
}
public Double getVlaue() {
return this.value;
}
public void setValue(Double salary) {
this.value = salary;
}
@Override
public Object clone() {
Employee emp;
emp = new Employee(this.lname, this.fname);
emp.setValue(this.value);
return emp;
}
@Override
public String toString() {
return this.getClass().getName() + "[" + this.fname + " " + this.lname + ", "
+ this.value + "]";
}
}
Output:
methodoverloading.Employee[Adams Smith, 40000.0]
methodoverloading.Employee[Adams Mark, 40000.0]
This was an example of how to create a clone class of a class in Java.
