The clone method is protected in Object class and each class created in java extends Object class. Now if we create a class and declare a method as protected then it's subclasses should be able to instantiate a base class object and call it.
But if we try to use the clone method it gives me an error that clone has protected access .why?
Subclasses can access a protected method via inheritance only (if they're in a different package, which they are in this case). That means, you can access it from within the object that is inheriting it, but not from outside that object (even if it's within the same class).
So, for instance, this is allowed:but what you're doing there is not.
The semantics of "protected" are subtle, and a lot of people don't quite understand them. To say that a protected method may be called by child classes is actually not quite right. A protected method of a parent class may be called by code in a child class on a reference whose type is at least that of the child class. In other words, if B extends A and A extends Object, then code in A can call clone() on instances of A or B, but not on instances of Object itself.
The reason that your first example compiles is because both A and B are in the same package; within a package, all classes may call the protected members of all other classes, regardless of inheritance. If you put A and B into different packages, the example would not compile, just the same as the A/Object example.
Regarding the clone() method itself: to make clone() generally usable on a class, you must override it and make it public; you must also mark the class with the "Cloneable" interface. That's simply how clone() is designed -- most folk these days think it's a bad design.
In addition, once you've got round that you'll hit a second problem. If you look up the Javadocs for the clone method, you'll see that it will throw, by default, a CloneNotSupportedException if the object doesn't implement Cloneable.
The convention is, to make a class you can clone, you should do the following:
- implement Cloneable - override clone() with a public version (allowing you to clone it from outside)
- either call super.clone(), or do all the cloning yourself (or a mixture), depending on the exact requirements.
Look up the Cloneable interface definition for more details.