class TestReferenceandValue
{
private void test(int a){
a = 10;
}
public static void main(String[] args) {
TestReferenceandValue tav = new TestReferenceandValue();
int a = 3;
tav.test(a); //这里传递的参数a就是按值传递
System.out.println(a);
}
}
Console:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
class TestReferenceandValue
{
private static void test(int a){
a = 10;
}
public static void main(String[] args) {
int a = 3;
test(a);
System.out.println(a);
}
}
Console:
关于以上两段代码,想谈的知识点有2点:
1. 两段代码相比较结合着看想说明:Java中静态方法中只能调用静态成员(静态成员包括:静态方法和静态属性)
如果想在静态方法中调用非静态成员,必须先将包含该非静态承运的类,实例化后,再进行调用。
∵ 静态成员从属于类,而非静态成员从属于对象。
2. 只看其中任意一段代码想说明:为什么a从始至终值都是3?
答:按值传递重要特点:传递的是值的拷贝,也就是说传递后对“值的拷贝”所进行的任何操作,都不影响“原值”。
即:tav.test(a); 这行代码,是对a的拷贝所进行的,与原a无关,所以a仍为3.
按引用传递的重要特点:传递的是值的引用,也就是说传递前和传递后都指向同一个引用(也就是同一个内存空间)。
public class TestReferenceandValue {
public static void test1(A a){
a.age = 20;
}
public static void main(String[] args) {
TestReferenceandValue t = new TestReferenceandValue ();
A a = new A();
System.out.println(a.age);
t.test1(a);
System.out.println(a.age);
}
public static class A{
public int age = 5;
}
}
Console: