将对象引用传递给方法 [英] Passing object reference to a method

查看:42
本文介绍了将对象引用传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在 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.

在您的情况下,AempBe.

In your case, A is emp and B is e.

你可以在这个问题中找到一些很好的解释.

这篇关于将对象引用传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆