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: 32654
4
posted
0
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
posted
0
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: 32654
4
posted
0
It's not an example. It says in your link it won't work.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
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
posted
0
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
posted
0
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!