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 Employee has 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 new Employee object 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 Employee object 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button