1

I have a very simple question (I guess!) How can clone method be protected in Cloneable interface while interfaces can only declare public methods?

Hassan Khallouf
  • 1,170
  • 1
  • 13
  • 30
  • 2
    The `Cloneable` interface, and `clone` in general, is kind of _broken._ (Effective Java, item 11) – Louis Wasserman May 09 '12 at 23:17
  • @LouisWasserman What you say is absolutely true, but unrelated to the question :) See any answer below. But you are right, `clone` should be avoided in general. – Andres F. May 10 '12 at 14:54
  • The point is, the clone method being protected in the Cloneable interface is _part of why_ `Cloneable` is broken. – Louis Wasserman May 10 '12 at 18:22

4 Answers4

2

The Cloneable interface doesn't actually have any methods defined in it. It's simply a marker interface, similar to Serializable.

It's expected that any object that is actually cloneable will implement this interface, and override the clone() method from Object (to at minimum make it public access).

Perception
  • 79,279
  • 19
  • 185
  • 195
2

The Cloneable interface doesn't define any methods.
protected Object clone() is a method in java.lang.Object, which throws an exception if the class doesn't implement Cloneable.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

The Cloneable doesn't declare any methods :)

You are thinking of Object, which does declare a clone() method.

Andres F.
  • 403
  • 1
  • 13
  • 24
2

Cloneable is a marker interface it doesn't have any methods.

clone method is in Object class, since all objects in Java implicitly extends Object hence its available even if its protected.

If a class doesn't implement Cloneable and its clone method is called it will thrown CloneNotSupportedException

mprabhat
  • 20,107
  • 7
  • 46
  • 63