• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning

 
Sagar Jambhulkar
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this confusion abt cloning
//CloneTest.java
public class CloneTest{

public Object clone(){
//super.clone(); 1
return new CloneTest();

}

public static void main(String[] args){

CloneTest aClone=new CloneTest();
CloneTest bClone=(CloneTest) aClone.clone();

}

}

This compiles pefectly fine and i dont get CloneNotSupportedException?
But uncommenting super.clone() causes compilation error.CloneNot...
not caught.Does this mean if and only if you use Object.clone() in your clone implementaion you have to use the Clonenable interface?
Can someone explain the use of this (tagging?) interface,as there are no methods in this interface.
Thx in Advance.
 
soumya ravindranath
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Java API

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.


When your CloneTest calls super's ( Object ) clone() method, it throws this exception while compiling. What I am puzzled about is, why the API states that it's a runtime exception
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.lang.CloneNotSupportedException is called a 'compile-time checked exception'. There is a fierce debate (which seems to have concluded) about the validity of compile-time checked exceptions (i.e. it is agreed that they are a design flaw, otherwise, you don't have all the facts). Nonetheless, you have to put up with them in a Java context, since they are intrinsic to the language, and a great deal of the core API.

When you call a method that declares to throw a checked exception, it must be declared to be caught (with a try/catch block) or thrown (with the throws keyword).

Here is some more reading:
http://java.sun.com/docs/books/tutorial/essential/exceptions/
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic