-1

When I opened Object class source code I can see the clone() method in it.

When I try to see clone() method in the method list doesn't show up (If I create object of MyClass as myClass and apply . dot operator it gives me suggestion of all available methods in eclipse IDE but it doesn't show clone() method in that list!!)

MyClass myClass = new MyClass(); myClass. // here I expect to see clone() as well but not

why it happens ????

user3571396
  • 113
  • 2
  • 11

3 Answers3

1

If you consider official Oracle Java documentation for Object class you can find that the clone() method is protected, due to polymorphism this method will be able only in the same package or in the child class, but not the outside it.

So, the method would be able only in package java.lang and only in all children of this class, but not in the packages where children has been declared. Try to read this topic to rise you understanding about java access modifiers

But there is one thick here: you can make override of this method like this

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

and after that you be able to use method clone in the same package where declared your class MyClass, but be prepared to get CloneNotSupportedException

Also you be able to use your own implementation. Just implement Clonable interface and provide your own clone method.

Also, if you planing that the clonned object must be equals you also should override equals method too.

Good Luck!

Community
  • 1
  • 1
Oleh Dokuka
  • 11,613
  • 5
  • 40
  • 65
  • 1
    Protected can be seen outside of the package as well to the Child ...... and Object is Parent class for every single user created class ... so was thinking why its happening why they dont show clone method as well. – user3571396 Sep 30 '15 at 07:48
  • try to read [this](http://stackoverflow.com/questions/15939002/protected-access-modifier-in-java) – Oleh Dokuka Sep 30 '15 at 08:00
0

Perhaps the creator of the object you are trying to clone made the clone method private. Also you probably shouldn't rely on Eclipse autocomplete especially if you're just starting out with Java.

rparikh
  • 25
  • 5
  • this is best I think ..... better not to break head in it .. its choice of eclipse creators not to show protected methods as suggestions :) – user3571396 Sep 30 '15 at 07:58
0

The java.lang.Cloneable interface must be implemented by the class

MyClass implements Cloneable.

Niju
  • 487
  • 1
  • 9
  • 18