我不明白为什么要这样做:
public class Example {
private String name;
private String surname;
Example(String firstName, String secondName) {
name = firstName;
surname = secondName;
}
// whatever other code goes here
}
我不明白为什么需要设置 name = firstName
和 surname = secondaryName
。为什么我不能直接设置 name
和 surname
?
最佳答案
这些不是同一类型的变量:
firstName
和secondName
是方法参数。一旦方法结束,这些变量就会超出范围
另一方面,name
和surname
是类中的字段。只要实例存在,它们就保持“附加”到该类的实例。
以下是其含义的说明:
String a = "Hello";
String b = "World";
// For the duration of the constructor, a becomes firstName,
// and b becomes secondName
Example e = new Example(a, b);
// Once the constructor exists, firstName and secondName disappear.
// Resetting a and b after the call is no longer relevant
a = "Quick brown fox jumps";
b = "over the lazy dog";
System.out.println(e.getName()+" "+e.getSurname());
a
和 b
的值已更改,但存储在 Example
中的值仍设置为您传递给构造函数的值。
关于java - 为什么将一个变量赋值给另一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26167426/