我不明白为什么要这样做:
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 = secondName。为什么我不能直接设置name和surname?
发布于 2014-10-03 02:46:23
这些不是相同类型的变量:
firstName和secondName是方法参数。一旦方法结束,这些变量就会从scopename中消失,而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中的值仍然设置为您传递给构造函数的值。
https://stackoverflow.com/questions/26167426
复制相似问题