class Student
{
private String name ;
private String num;
public Student(String name , String num)
{
this.name = name;
this.num = num;
}
public Student modify(String name)
{
this.name =name;
return this;
}
public String toString()
{
return name + " "+num ;
}
}
public class StringTest
{
public static void test(String str)
{
str = str + " World!";
}
public static void test(Integer str)
{
str = new Integer(100);
}
public static void test(Student stu)
{
stu = stu.modify("zeiku");
}
public static void main(String []args)
{
String str = new String("Hello");
test(str);
prt(""+str);
Integer inte = new Integer(1000);
test(inte);
prt(""+inte.intValue());
Student stu = new Student("zhudonhua","3030612060");
test(stu);
prt(""+stu);
}
public static void prt(String str)
{
System.out.println(str);
}
}我自己定义一个类
运行结果:
Hello
1000
zeiku 3030612060Hello
1000
为什么不变啊??而 zeiku 3030612060 改变了啊?????
同样是函数参数的传递,是不是String等系统提供的类在参数传递时候进行了深拷贝啊????
我自己定义的类要想实现同样的功能是不是一定要实现Cloneable接口啊???
{
private String name ;
private String num;
public Student(String name , String num)
{
this.name = name;
this.num = num;
}
public Student modify(String name)
{
this.name =name;
return this;
}
public String toString()
{
return name + " "+num ;
}
}
public class StringTest
{
public static void test(String str)
{
str = str + " World!";
}
public static void test(Integer str)
{
str = new Integer(100);
}
public static void test(Student stu)
{
stu = stu.modify("zeiku");
}
public static void main(String []args)
{
String str = new String("Hello");
test(str);
prt(""+str);
Integer inte = new Integer(1000);
test(inte);
prt(""+inte.intValue());
Student stu = new Student("zhudonhua","3030612060");
test(stu);
prt(""+stu);
}
public static void prt(String str)
{
System.out.println(str);
}
}我自己定义一个类
运行结果:
Hello
1000
zeiku 3030612060Hello
1000
为什么不变啊??而 zeiku 3030612060 改变了啊?????
同样是函数参数的传递,是不是String等系统提供的类在参数传递时候进行了深拷贝啊????
我自己定义的类要想实现同样的功能是不是一定要实现Cloneable接口啊???
他们的传递,是值传递,同样的类型还有Char,Floar,Double等等作为原始类型的Wrapper class.
Over,
//这个时候str已经不再指向原来的对象,而是重新创建了一个新的String对象,newStr != strStudent newStu = stu.modify("zeiku");
//你的代码中是return this 所以newStu == stu
注意上面是 == 表示是仍然指向同一个对象
public static void test(String str)
{
str = str + " World!";
}
我是把新生成的对象空间的引用又交给了str啊!
本来, 参数 str 确实指向了 原来的字符串, 但是后来你让它指向了新的 : str+" World !" 这是个新串,不是原来那个, 因为 Java 中 String 是 immutable , 任何修改操作都得到一个新的串.
{
str = str + " World!";
}
我是把新生成的对象空间的引用又交给了str啊!
没错,就是因为你改变的是 str的指向,而不是它原来指向的值,正因为如此才不会影响外面的变量(它的指向不会受到函数内部的修改而改变)