有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将对象引用传递给方法

如果changedetails()中的Employee引用为null,则会保留变量id值,并且不会引发NullPointerException(代码1),这可能是因为我们只传递了对象引用的副本,但在代码2中,变量值为什么会更改

代码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);
    }
}

共 (4) 个答案

  1. # 1 楼答案

    1. 在java中,对对象的引用是按值传递的

    所以

    public static void main(String args[])
    {
        Employee emp = new Employee("Vishal",7);
        changedetails(emp);  / /object Employee ahs only one reference - "emp"
        System.out.println(emp.id);
    }
    
    
    public void   changedetails(Employee emp1){ // here both emp1 and emp of main() point to the same Employee object.
    emp1.setId(100); // now since emp1 also points to same Employee object, the data will be changed.
    emp1 = null;// now emp1 points to null. So, only emp is pointing to E,ployee
    
    }
    
  2. # 2 楼答案

    In both cases Reference 'e' in changedetails() and 'emp' in main() both point to same object.

    代码(1)

    在changedetails()中,当您使e=null时;只有e停止指向对象。但emp继续指向目标。所以在main()中,当你做emp时。id值打印,无NullPointerException

    代码(2) 在changedetails()中,当您将e.id=9时,请记住两个引用都指向同一个对象,即
    changedetails()中的“e”和main()中的“emp”指向同一个对象。。。。 因此,e.id=9意味着在执行emp时对同一对象进行的更改。main()中的id值为9

  3. # 3 楼答案

          -------- 
    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

    这就是为什么如果您从引用A访问id,它不会抛出NullPointerException。你所困惑的只是对象的引用和内存中对象引用

    在你的例子中,AempBe

    You can find some good explanation in this question.

  4. # 4 楼答案

    传递给方法changedetails()的参数是它自己的变量,与main()方法中的变量emp不同。他们都指的是同一个eployee。因此,如果您引用员工并更改其状态,那么更改在changedetails()main()两种方法中都可见。但是,如果将null赋值给方法changedetails()的参数变量,这是一个仅在该方法中可见的局部更改

    旁注:更改方法参数的值被认为是不好的做法。离开方法changedetails()后,方法参数就消失了,因为它们位于堆栈上,而不是堆上