What is clone() method?

What is clone() method?

Postby Kishan » Fri Feb 01, 2013 5:35 am

What is clone() method?
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am

Re: What is clone() method?

Postby Rose » Mon Feb 04, 2013 3:52 am

Using clone() method you can copy of an object. You must implemt cloneable interface
Rose
 
Posts: 20
Joined: Tue Jan 29, 2013 5:16 am

Re: What is clone() method?

Postby Kishan » Thu Feb 07, 2013 6:00 am

Code: Select all
package javatrng.examples.basics;

public class CloneExample {

   public static void main(String[] args) throws CloneNotSupportedException {
      Name n = new Name();
      n.setFirstName("Rajesh");
      n.setLastName("Kumar");
      System.out.println(n.getFirstName() +" "+ n.getLastName());
      
      Name clonedObject = (Name)n.clone();
      System.out.println(clonedObject.getFirstName() +" "+ clonedObject.getLastName());
      
      System.out.println(n +" - "+clonedObject);
   }

}


class Name implements Cloneable {
   String firstName;
   String lastName;
   
   Name() {
      System.out.println("constructor");
   }
   
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   
   @Override
   public Object clone() throws CloneNotSupportedException {
      return super.clone();
   }
}
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am


Return to Core Java

Who is online

Users browsing this forum: No registered users and 1 guest

cron