Java 编程语言只由值传递参数当一个对象实例作为一个参数被传递到方法中时,参数的值就是对该对象的引用。对象的内容可以在被调用的方法中改变,但对象的引用是永进不会改变的。
下面的代码例子可以阐明这一点:
代码片段:
public class ValuePass {
float ptValue;
//方法来更改当前值
public void changeInt(int value) {
value = 55;
}
public void changeStr(String value) {
value = "different";
}
public void changeObjValue(ValuePass ref) {
ref.ptValue = 99.0f;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str;
int val;
//创建类的实例
ValuePass pt = new ValuePass();
//分配整型数
val = 11;
//试着去改变它
pt.changeInt(val);
//正确的值是什么?
System.out.println("Int value is:" + val);
//分配1字符串
str = "hello";
//试着去改变它
pt.changeStr(str);
//正确的值是什么?
System.out.println("Str value is" + str);
//现在设置 ptvalue
pt.ptValue = 101.0f;
//现在改变浮点数的值
//通过对象引用
pt.changeObjValue(pt);
//现在的值是多少?
System.out.println("Current ptValue is:" + pt.ptValue);
}
}
运行结果: