该语句mn.goo(pi)
传递值的副本,86
同时mn.show(wi)
传递包含相同对象的引用变量的副本。
- 为什么我可以这样做?wi++ 或 wi +=2 。我的意思是为什么编译器像普通的原始变量一样处理那些引用变量?(引用变量不存储对象的引用吗?)
由于 and 的概念autoboxing
,auto-unboxing
转换wi
为primitive
,递增,然后转换回Wrapper
2.或者如果我们有==>" Integer wi = new Integer("56") " 和 "int pi = 56" 。为什么 (wi == pi) 返回 true。不应该存储引用(地址)
这是因为对于Integer
包装类,==
直到的值将返回 true 128
。这是设计使然
对于您对 passign 原语和对象引用的疑问,请研究这些程序
class PassPrimitiveToMethod
{
public static void main(String [] args)
{
int a = 5;
System.out.println("Before Passing value to modify() a = " + a);
PassPrimitiveToMethod p = new PassPrimitiveToMethod();
p.modify(a);
System.out.println("After passing value to modify() a = " + a);
// the output is still the same because the copy of the value is passed to the method and not the copy of the bits like in refrence variables
// hence unlike the reference variables the value remains unchanged after coming back to the main method
}
void modify(int b)
{
b = b + 1;
System.out.println("Modified number b = " + b);
// here the value passed is the copy of variable a
// and only the copy is modified here not the variable
}
}
输出是
Before Passing value to modify() a = 5
Modified number b = 6
After passing value to modify() a = 5
将对象引用传递给方法
class PassReferenceToMethod
{
public static void main(String [] args)
{
Dimension d = new Dimension(5,10);
PassReferenceToMethod p = new PassReferenceToMethod();
System.out.println("Before passing the reference d.height = " + d.height);
p.modify(d); // pass the d reference variable
System.out.println("After passing the reference d.height = " + d.height);
// the value changes because we are passing the refrence only which points to the single and same object
// hence the values of the object are modified
}
void modify(Dimension dim)
{
dim.height = dim.height + 1;
}
}
输出是
class PassReferenceToMethod
{
public static void main(String [] args)
{
Dimension d = new Dimension(5,10);
PassReferenceToMethod p = new PassReferenceToMethod();
System.out.println("Before passing the reference d.height = " + d.height);
p.modify(d); // pass the d reference variable
System.out.println("After passing the reference d.height = " + d.height);
// the value changes because we are passing the refrence only which points to the single and same object
// hence the values of the object are modified
}
void modify(Dimension dim)
{
dim.height = dim.height + 1;
}
}
输出是
Before passing the reference d.height = 10
After passing the reference d.height = 11