0

I was trying to override clone method in my class "Employee", when super.clone() was called, it gave exception but same code worked when I implemented "clonable". What my question is, every class has base class "Object". But when we call super.clone() it fails and on implementing clonable it works. why is it so?

Like shouldn't base class method can be accessible using "super" from subclass? why does it throws runtime exception?

public class Employee {
    //explicit Employee extends Object didn't worked. 
    String name;
    Integer id;
    public Employee(String name, Integer id) {
       this.name = name;
       this.id = id;
     }
    @Override
    protected Object clone() throws CloneNotSupportedException {
      return super.clone();
    }
  }
Kaustubh_Kharche
  • 725
  • 3
  • 13
  • 34
  • hint: how do we know that Employee can be cloned? – ΦXocę 웃 Пepeúpa ツ Nov 15 '17 at 05:08
  • This is the way the language was designed. If the language designers were to answer your question, how would that help you? This is like asking why a particular keyword has a particular meaning... it does because that's the way it was defined. – Jim Garrison Nov 15 '17 at 05:10
  • If Obejct class has not implemented clone() method as per documentation, then what does 'suer.clone()' means in Employee class? – OwlR Mar 07 '20 at 09:50

2 Answers2

1

Check out stackoverflow answer:

The implementation of clone() in Object checks if the actual class implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement Cloneable and downcast the result of super.clone() to your class. Another burden is that the call to super.clone() can throw a CloneNotSupportedException that you have to catch, even though you know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are an obvious case of object-oriented design gone wrong.

Bhushan Uniyal
  • 5,575
  • 2
  • 22
  • 45
  • This answer is nothing more than a reference to another SO question. You should instead vote to closer this question as a duplicate. – yshavit Nov 15 '17 at 05:40
0

To answer your question, just take a look at the Object class reference page, and you'll see this:

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.

So the behavior you described is exactly what Java is defined. Not sure what else is confusing here.

Dat Nguyen
  • 1,626
  • 22
  • 25