StringBuffer为什么不能克隆?
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = buffer.clone();
要什么样的对象才能进行克隆?
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = buffer.clone();
要什么样的对象才能进行克隆?
Test t=new Test();
Test tmp;
if(t instanceof Cloneable)
{
tmp=t.clone();
}
package zhao;public class testClone implements Cloneable { /**
* @param args
*/
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
StringBuffer buffer2 = (StringBuffer)sb.clone(); // 因为clone()方法是protected类型的,所以不能在另一个类中使用StringBuffer的clone方法,没发实现 }
}
你要克隆对象得做 2件事情
第一:要实现Cloneable接口(红色部分)
第二:重写(覆盖)clone方法(红色部分)代码如下:
package zhao;public class TestClone implements Cloneable { /**
* @param args
*/
public static void main(String[] args) {
TestClone t = new TestClone();
TestClone t1 = (TestClone)t.clone(); }
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}}
package zhao;public class TestClone implements Cloneable { /**
* @param args
*/
public static void main(String[] args) {
TestClone t = new TestClone();
TestClone t1 = (TestClone)t.clone(); }
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}}
因为有些类已经实现好了,所以不用自己写代码