为什么要将变量赋给另一个变量?

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 = firstNamesurname = secondName.为什么我不能只是设置namesurname直接?

das*_*ght 5

这些变量不是同一种:

  • firstName并且secondName是方法参数.方法结束后,这些变量就超出了范围
  • namesurname另一方面,是一个类中的字段.只要实例存在,它们就会"附加"到该类的实例.

以下是这意味着什么:

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)

ab已更改,但存储的值Example仍设置为传递给构造函数的值.