为什么对象属性在Java的updateObject()方法中没有更新?
Why is the object property not updated in the updateObject() method in Java?
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”?请帮忙。
如果您在 IDE 中看到,您可能会收到来自
的警告
updateEmployee() method
说明,
The return value is not used anywhere, you can make the return type as void
因为Java总是按值传递,如果你需要更新对象的状态,那么分配return(更新的)值回到它。
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
ref.
会更好
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);
}
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”?请帮忙。
如果您在 IDE 中看到,您可能会收到来自
的警告updateEmployee() method
说明,
The return value is not used anywhere, you can make the return type as void
因为Java总是按值传递,如果你需要更新对象的状态,那么分配return(更新的)值回到它。
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
ref.
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);
}