【问题标题】:Why is the object property not updated in the updateObject() method in Java? [duplicate]为什么Java中的updateObject()方法中对象属性没有更新? [复制]
【发布时间】:2020-10-21 13:40:25
【问题描述】:
public class Employee {

    int age = 32;
    String name = "Kevin";

    public Employee updateEmployee(Employee e) {
        e = new Employee();
        e.age = 56;
        e.name = "Jeff";
        return e;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee t = new Employee();
        t.updateEmployee(t);
        System.out.println("age= " + t.age + " " + "name= " + " " + t.name);

    }

}

====================

OUTPUT:-
age= 32 name=  Kevin

为什么输出不是 56 和 Jeff。我更新了方法中的对象引用“t”?请帮忙。

【问题讨论】:

  • 您创建了一个新员工,与传入的t 不再有任何关系。
  • 你为什么要e = new Employee();

标签: java oop object methods arguments


【解决方案1】:

如果您在 IDE 中看到,您可能会收到来自 IDE 的警告,

updateEmployee() method

陈述,

The return value is not used anywhere, you can make the return type as void

由于Java始终是按值传递的,如果您需要更新对象的状态,则将返回(更新的)值赋回给它。

public static void main(String[] args) {
    Employee t = new Employee();
    t = t.updateEmployee(t);
    System.out.println("age= " + t.age + " " + "name= " + " " + t.name);
}

输出:

age= 56 name=  Jeff

Edit: 如果您的更新方法只适用于 this 参考,那就更好了。

public void updateEmployee() {
    this.age = 56;
    this.name = "Jeff";
}

public static void main(String[] args) {
    Employee t = new Employee();
    t.updateEmployee();
    System.out.println("age= " + t.age + " " + "name= " + " " + t.name);
}

【讨论】:

  • 嗨,我同意这一点。我只是想指出缺少的东西@Ivar
  • 我的错..是的..
猜你喜欢
  • 2021-07-17
  • 2017-02-07
  • 2019-03-02
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多