fork download
  1.  
  2. class Book implements Cloneable
  3. {
  4. private String title;
  5. private int pageCount;
  6.  
  7. public Book()
  8. {
  9. title = "";
  10. pageCount = 0;
  11.  
  12. }
  13. public Object clone() throws CloneNotSupportedException
  14. {
  15. Book objClone = new Book();
  16. objClone.setTitle(this.title);
  17. objClone.setPageCount(this.pageCount);
  18. return objClone;
  19. }
  20.  
  21. public void setTitle(String title)
  22. {
  23. this.title = title;
  24. }
  25. public void setPageCount(int pageCount)
  26. {
  27. this.pageCount = pageCount;
  28. }
  29. public String toString()
  30. {
  31. return "Book title : "+title +" Number of pages : "+pageCount;
  32. }
  33. }
  34. class TestBook
  35. {
  36. public static void main (String[] args) throws CloneNotSupportedException
  37. {
  38.  
  39. Book b1 = new Book();
  40. b1.setTitle("Programming in Java");
  41. b1.setPageCount(466);
  42.  
  43. Book b2 = new Book();
  44. b2 = (Book)b1.clone(); // creating clone of b1 and assign it to b2
  45.  
  46. System.out.println(b2);
  47. }
  48. }
Success #stdin #stdout 0.14s 36220KB
stdin
Standard input is empty
stdout
Book title : Programming in Java Number of pages : 466