class Copy
{
public static void main(String[] args)
{
CopySub sub=new CopySub("abc",18);
CopySub test=(CopySub)sub.clone();
test.name="def";
test.age=16;
System.out.println("test's name is"+test.name+"and"+"age is "+test.age);
}
}class CopySub implements Cloneable
{
String name;
int age;
CopySub(String name,int age)
{
this.name=name;
this.age=age;
}
protected Object Clone() throws CloneNotSupportedException
{
Object o= null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}在编译的时候会出现 :
D:\Test>javac Copy.java
Copy.java:6: clone() 可以在 java.lang.Object 中访问 protected
CopySub test=(CopySub)sub.clone();
谢谢!
{
public static void main(String[] args)
{
CopySub sub=new CopySub("abc",18);
CopySub test=(CopySub)sub.clone();
test.name="def";
test.age=16;
System.out.println("test's name is"+test.name+"and"+"age is "+test.age);
}
}class CopySub implements Cloneable
{
String name;
int age;
CopySub(String name,int age)
{
this.name=name;
this.age=age;
}
protected Object Clone() throws CloneNotSupportedException
{
Object o= null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}在编译的时候会出现 :
D:\Test>javac Copy.java
Copy.java:6: clone() 可以在 java.lang.Object 中访问 protected
CopySub test=(CopySub)sub.clone();
谢谢!
还有就按照惯例,实现此Cloneable接口的类应该使用公共方法重写 Object.clone
这里把clone的protected改成public是不是更好呢?
public class Copy {
public static void main(String[] args) throws CloneNotSupportedException {
CopySub sub = new CopySub("abc",18);
CopySub test = (CopySub) sub.Clone();
test.name = "def";
test.age = 16;
System.out.println("test's name is"+test.name+" and"+"age is "+test.age);
}
}
public class CopySub implements Cloneable{
String name ;
int age ;
CopySub(String name,int age) {
this.name = name ;
this.age = age;
}
protected Object Clone()throws CloneNotSupportedException {
Object o = null ;
try{
o = super.clone();
}catch(CloneNotSupportedException e){
//e.printStackTrace();
System.out.println(e.toString());
}
return o ;
}
}
另外想说明的是,小弟没有分数可以给!