日期:2014-05-20  浏览次数:20652 次

关于String对象的clone方法
String对象也是对象啊,为什么不能象其它对象那样可能呢?

------解决方案--------------------
protected比package权限多一点的地方就在于可以被子类引用。但它同package一样不能被非该包中的其他类引用。
String所在的 包为java.lang.String,而你自己写的类却不在这个包中,所以你不能访问到clone方法。
举个例子:
package com.sina.www;
public class A{
protected void function(){}
}

package com.sina.www;
public class B extends A{}
}

package com.sina.www;
public class AppOne{
public static void main(String[] args){
B b = new B();
b.function();//这是正确的。
}
}

package net.nytimes.www;
public class AppTwo{
public static void main(String[] args){
B b = new B();
b.function();//错误。因为不在同一包中。这和你所说的情况是一样的
}
}
------解决方案--------------------
class Student implements Cloneable
{
String name;
int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}


=======================
实际上我想这里实现的一样是浅克隆, 不过由于 String 是一个特殊的类, 它是不可见的, 问题就在这里, 假设原来的Student的实例为s1, 再克隆出一个s2出来, 当我们修改s1.name的值时,实际上是创建一个新的name,再赋值给s1.name, 所以s2.name的值并没有受到影响, 不过这到底应该理解为深克隆还是浅克隆呢? 我也说不清楚了
------解决方案--------------------
class Student implements Cloneable
{
String name;
int age;
public Object clone(){
Student o = null;
try{
o = (Student)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return o;
}


//这是浅clone;


class Student implements Cloneable
{
String name;
int age;
public Object clone(){
Student o = null;
try{
o = (Student)super.clone();

}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return o;
}


//这是浅clone;


public Object clone(){
Student o = null;
try{
o = (Student)super.clone();
//因为String 类是final的,故没有覆盖clone方法;
//不能这样写:o.name= (String)name.clone();
o.name=name.subString(0,name.length());
//或o.name=new String(name);
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return o;
}

//这样就是深clone



------解决方案--------------------
STRING类是一个特殊的类
他的定义是FINAL的
而且,他的一些操作符也全都重写过的

JAVA的意思就是让你把STRING当作基础变量来用
他的表现和int,long这些基础类型是一样的