wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes protected clone() doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "protected clone() doubt" Watch "protected clone() doubt" New topic
Author

protected clone() doubt

Vijay Raj
Ranch Hand

Joined: Oct 10, 2005
Posts: 110
Hello,

I was reading about clone() from Thinking in Java.
TIJ3

There is an example (given below) which gives a compile time error that says clone() is not accessible.
Integer x = new Integer(1);
x = x.clone();

My question:

1. Why is not clone() accessible. Every class in Java automatically extends java.lang.Object which means that protected methods such as clone() should be accessible.

regards,
vijay.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
Welcome on board.

I am not sure why you are having problems, but why are you setting x to be a clone of itself?

CR
Vijay Raj
Ranch Hand

Joined: Oct 10, 2005
Posts: 110
It was just an example. You can take any other class which does not override clone(). Click on the link in my first post, you'll see the example there.

The clone method() in java.lang.Object copies bit by bit. Its protected there. So any class in the same java.lang package and any other class that inherits java.lang.Object can access the clone() method. Then why do we get an error saying that clone method is not accesible.

regards,
vijay.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
It's not an example. It says in your link it won't work.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
There is another thread on this forum, active today, where there is more discussion about clone() being protected.
Dan Patterson
Greenhorn

Joined: Jan 27, 2005
Posts: 24
You have to implement the Cloneable interface in your class with the object you wish to clone.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
I think your question is more about protected access than about the clone
method itself. As far as class Integer is concerned, Method clone is just an
another example of a proteced method. So, we could as easily use the following
example:Your question then is why can't you do the following:But do you understand why that line violates protected
access if it is written in a class outside package widget?

Going back to Integer, one could also ask, "why isn't the clone method in
Integer public?". (The original post was rather vague and it's not clear
what was really being asked there.) Well, Integer is an example of an
immutable class, like String, so there is no reason to clone instances!


There is no emoticon for what I am feeling!
 
Consider Paul's rocket mass heater.
 
subject: protected clone() doubt