use*_*999 0 java variable-assignment
我不明白为什么这样做:
public class Example {
private String name;
private String surname;
Example(String firstName, String secondName) {
name = firstName;
surname = secondName;
}
// whatever other code goes here
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我需要设置name = firstName和surname = secondName.为什么我不能只是设置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());
Run Code Online (Sandbox Code Playgroud)
值a和b已更改,但存储的值Example仍设置为传递给构造函数的值.
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |