问题描述
如果在 changedetails() 中将 Employee 引用设为 null,则保留变量 id 值并且不抛出 NullPointerException(代码 1)可能是因为我们只是传递了对象引用的副本,但在代码 2 中为什么变量值改变了
If the Employee reference is made null in the changedetails(), variable id value is retained and NullPointerException is not thrown (Code 1) may be because we just pass a copy of object's reference, but in Code 2 why the variables value has changed
代码 1:
public class JavaPassing {
public static void changedetails(Employee e)
{
e=null;
}
public static void main(String args[])
{
Employee emp = new Employee("Vishal",7);
changedetails(emp);
System.out.println(emp.id);
}
}
代码 2:
public class JavaPassing {
public static void changedetails(Employee e)
{
e.id=9;
}
public static void main(String args[])
{
Employee emp = new Employee("Vishal",7);
changedetails(emp);
System.out.println(emp.id);
}
}
推荐答案
--------
A -->| Object |<-- B
--------
A.id = 10; // Property of object modified
B.id = 10; // Property of object modified here also
B = null ; // B is set to null
--------
A -->| Object | B (reference is null)
--------
这里当你将B
设置为null
时,A
没有被修改它会继续指向Object
在堆中.
Here when you set B
to null
, A
is not modified it will continue to point the Object
in heap.
这就是如果您从引用 A
访问 id
不会抛出 NullPointerException
的原因.您所混淆的只是对象的引用和内存中的对象.
And that is why it will not throw NullPointerException
if you will access id
from reference A
. All you are confused is between reference of Object and Object in memory.
在您的情况下,A
是 emp
而 B
是 e
.
In your case, A
is emp
and B
is e
.
这篇关于将对象引用传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!