0

Attaching the snippet of clone method implementation from object class, although object class does not implement cloneable interface, how is it allowed to use it ? Another one : Why couldn't clone method could stay in cloneable interface instead of object class ? What's the significance and importance aka real time application of marker interface which a usual interface could not have provided.

[clone method from object class] [1]: https://i.stack.imgur.com/QH4Yi.png

  • Please read: [Can I ask only one question per post?](https://meta.stackexchange.com/questions/222735/can-i-ask-only-one-question-per-post) --- [The `Cloneable` interface is regarded broken](https://www.artima.com/articles/josh-bloch-on-design). – Turing85 Jul 31 '21 at 13:54
  • 1
    Please read: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Turing85 Jul 31 '21 at 13:59

1 Answers1

-1

although object class does not implement cloneable interface, how is it allowed to use it ?

Search the web for what the cast operator does. It is a Cloneable.

Why couldn't clone method could stay in cloneable interface instead of object class ?

Because interfaces can't declare implementations (since java 1.8 they can via the default mechanism, but Object.clone() predates that by over 20 years or so).

Do not look at the way Cloneable works as an example of good API design. It's not, but the developers of java didn't know any better back when the Cloneable stuff was designed.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • False. `java.lang.Object` does not implement `Cloneable`. Subclasses *may,* and that's why the case *may* work, and that's why the `instanceof` test is present. If what you wrote was correct it wouldn't be necessary. – user207421 Aug 01 '21 at 10:30
  • @user207421 - There is a _cast_ in the code, mate. The question is: How is this code allowed to act as if it is a Cloneable: Because it is one - if it hadn't been, the code wouldn't have gotten there (the cast would have failed instead). – rzwitserloot Aug 01 '21 at 11:30
  • Exactly. And the cast has to be there because `Object` does not implement `Cloneable`, contrary to what it says in your first sentence. – user207421 Aug 03 '21 at 10:25