Clone() has protected access in java.lang.Object

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
on
Hi,
I created a class dummy and created and object like :
dummy dummy = new dummy();
dummy.clone();
The above statement is giving the error : Clone() has protected access in java.lang.Object..
Why is that...  Since all classes are implicitly subclass of Object.. protected method should be accessible from dummy...
If i create a class dum2 extends dummy... and place a protected method in dummy..
then i can access dum2.protectedMethod()....
Why is that in case of dummy its not working i am unable to access the protected method of Object class which is implicitly a superclass of dummy.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Because the Object class does not support the Cloneable interface.
I'm not really sure what code you are writing that causes that error.

This works for me:

public class ClassTest {
	public static void main(String[] args) throws CloneNotSupportedException {
		ClassTest t = new ClassTest() ;
		t.clone();
	}
}

Open in new window


and throws the CloneNotSupportedException when I call it - which is the default for Object (as krakatoa pointed out).

Doug
As Doug said, depends what you are aiming at

public class Cl{

	public class ClassTest implements Cloneable{
		protected Object clone(){return this;}
	}
	
		public static void main(String[] args) {
			ClassTest t = (new Cl()).new ClassTest() ;
			ClassTest t1 = (ClassTest)t.clone();
			System.out.println(t1 instanceof ClassTest);
			System.out.println(t1.hashCode() == t.hashCode());
		}
	
}

Open in new window

Mind you - I'm not quite so sure what is going on here, if you add/try :

Object o = t.clone();
			System.out.println(o instanceof ClassTest);

Open in new window

Seemed like a reasonable answer...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial