java code a
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String s){
s=s+"world";
}
}
java code b
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String q){
s=q+"world";
}
}
java code c
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
{
s+="world";
}
}
为什么ab代码的值不一样? c这样写为什么能运行
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String s){
s=s+"world";
}
}
java code b
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String q){
s=q+"world";
}
}
java code c
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
{
s+="world";
}
}
为什么ab代码的值不一样? c这样写为什么能运行
void methoda(String s){
s=s+"world";
}
操作的只是String s
而b里面操作的一直是 static String s="hello";
c的写法是会在类加载时就会执行
{
s+="world";
}
里的东西
1。String类型是不可变类型
2。pass by value的两种情况
void methoda(String s){
s=s+"world";
}
中有效
b代码中的局部变量变成了q,这时
void methoda(String q){
s=q+"world";
}
静态全局变量s 变成了局部变量q+"world"了
c中是代码块
{
s+="world";
}
因为是在main函数中通过mm.methoda(s);
来调用方法:methoda(String s)的(String传递的是引用)所以此时静态s和methoda中的s应该指向同一个堆内存才对呀,所以对methoda中的s 的修改应该也会反应到 静态s 中才对呀,实在搞不懂了,请解释一下:
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String s){
s=s+"world";
}
}
这里method方法中的s是局部变量,它把静态全局变量s隐藏了,就这个类来说,这个方法几乎什么都没有做;
java code b
public class m{
static String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(s);
System.out.println(s);
}
void methoda(String q){
s=q+"world";
}
}
这里method方法中的s是静态全局变量;
例如:在a中的这个mm.methoda(s);调用语句,的括号里面的参数s,指的是静态变量s的值“hello”通过拷贝一份既为“hello”作为实参转递给函数methoda(String s)其中s="hello"
即实际上mm.methoda(s);这条语句执行时就是"hello"="hello"+"world".
所以静态的变量的s根本就没作用到。
明白了这个你下面的都应该明白了吧!!!
a的程序你也可以改成下面这个
class m{
String s="hello";
public static void main(String args[])
{
m mm=new m();
mm.methoda(mm.s);
System.out.println(mm.s);
}
void methoda(String s){
this.s=s+"world";
}
}
希望你能为此把函数的调用掌握。。