Yes, he does know that. Look here
David Newton wrote:And why there's no need to say new String("xxx").
seetharaman venkatasamy wrote:
Ravi Pavan wrote:
String str2 = (String) str1.clone();
Can anybody please tell me why the above code is not getting compiled ??
your class need to implements Cloneable interface
I am completely lost out here. How does implementing the Cloneable interface for the Main class help - it still would not make String Cloneable would it?
Campbell Ritchie wrote:
And you doubtless know why String doesn't implement Cloneable.
No idea here. Why not?
For the same reason you don't need a copy constructor for the String class.
Ravi Pavan wrote:Please tell me why doesn't it so ??
A quick perusal of the API (you only need to read about 5 sentences) will give you a hint. Then you can tell us what you think!
Then you can tell us what you think
The String class does not allow you to clone String objects because Java has a policy where it shares a single String object among multiple references, and cloning violates that policy.
Sam Mercs wrote:
Campbell Ritchie wrote:For the same reason you don't need a copy constructor for the String class.
The String class does have a copy constructor right?
Yes it does. There is the String(String) constructor.
Frankly I still don't get the reason why the String class should not have been cloneable?
Because you will never need to clone strings. They are immutable, so their contents can never change. If String would have been Cloneable, you could clone an immutable String, and you would get another object that will forever be exactly equal to its source. Cloneable only makes sense for objects that can change, and you want to "fork" the object at a specific state.
Now logically, the copy constructor wouldn't be necessary either, but I think they let it exist for reflection issues. It surely isn't needed.
But String is a "library" class; they would give it a large public interface, including things like the copy constructor, even though 99.9% of users can see no point in using it, just in case somebody wants it.
And while we're on about copy constructors, did you work out why you weren't getting == to return true on Strings on your other thread?