若要使用Object对象中的clone方法需要实现Cloneable接口,
public class CloneObject {
public static void main(String[] args) {
CloneDemo obj1 = new CloneDemo(1);
CloneDemo obj2 = null;
try {
obj2 = (CloneDemo) obj1.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(obj1.getX());
System.out.println(obj2.getX());
}
}
class CloneDemo implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
private int x;
public CloneDemo(int x) {
super();
this.x = x;
}
public int getX() {
return x;
}
}