cloning stringbuffer

hi

here is my code and when I compile, I got error

Can someone tell me why?

class C

{

static public void main(String [] args)

{

try {

StringBuffer sb2 = new StringBuffer("Test");

StringBuffer sb3 = (StringBuffer) sb2.clone();

System.out.println(sb2 + " - " + sb3);

}

catch (Exception e) {System.out.println(e);}

}

}

C.java:6: Can't access protected method clone in class java.lang.Object. java.lang.StringBuffer is not a subclass of the current class.

StringBuffer sb3 = (StringBuffer) sb2.clone();

[611 byte] By [jacinle] at [2007-9-26 2:51:09]
# 1

The .clone() method has protected access so it can only be used by StringBuffers subclasses, StringBuffer is a final class so cannot be extended so clone() is not possible.

Why not use:

StringBuffer sb2 = new StringBuffer("Test");

StringBuffer sb3 = new StringBuffer(sb2.toString());

System.out.println(sb2 + " - " + sb3);

samlewis23 at 2007-6-29 10:38:16 > top of Java-index,Archived Forums,Java Programming...
# 2

StringBuffer does not implement the clone method, so it gets it from the Object class, where clone is defined as protected.

Also, StringBuffer does not implements the Cloneable interface, so if you could call the method you will receive a CloneNotSupportedException.

If you really need it, you can write a subclass of StringBuffer implementing Cloneable and a public clone method, but I think it is easier to do sb3 = new StringBuffer(sb2.toString()). Not exactly the same thing, because sb3 will not have the same capacity, but very similar.

U063667 at 2007-6-29 10:38:16 > top of Java-index,Archived Forums,Java Programming...
# 3
samlewis23 is right, you cannot extend StringBuffer. Sorry.
U063667 at 2007-6-29 10:38:16 > top of Java-index,Archived Forums,Java Programming...
# 4
see http://www.javaranch.com/ubb/Forum33/HTML/002217.html
agedashi at 2007-6-29 10:38:16 > top of Java-index,Archived Forums,Java Programming...
# 5
hithx so muchi got it clearly=>so => thxJacinle
jacinle at 2007-6-29 10:38:16 > top of Java-index,Archived Forums,Java Programming...