Java program for Cloning

By: Issac Emailed: 1788 times Printed: 2623 times    

In this tutorial we are going to see the use of clone method. In this example we are going to see how to use Clone method for BankCustomer. 

public class CloneExample
  {
   public static void main(String[] args) {
    BankCustomer cus1 = new BankCustomer("Angel", "S");
    cus1.setSalary(90000.0);
    BankCustomer cus2 = (BankCustomer) cus1.clone();
    cus1.setLastName("Mathew");
    System.out.println(cus1);
    System.out.println(cus2);
  }
}

class BankCustomer {
  private String lastName;

  private String firstName;

  private Double salary;

  public BankCustomer(String lastName, String firstName) {
    this.lastName = lastName;
    this.firstName = firstName;
  }

  public String getLastName() {
    return this.lastName;
  }

  public void setLastName(String lastName) {

    this.lastName = lastName;
  }

  public String getFirstName() {
    return this.firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public Double getSalary() {
    return this.salary;
  }

  public void setSalary(Double salary) {
    this.salary = salary;
  }

  public Object clone() {
    BankCustomer cus;
    cus = new BankCustomer(this.lastName, this.firstName);
    cus.setSalary(this.salary);
    return cus;
  }

  public String toString() {
    return this.getClass().getName() + "[" + this.firstName + " " + this.lastName + ", "
        + this.salary + "]";
  }
}

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial