是否可以通過簡單地使用構造函數的參數實例化類來設置類變量?你可以在構造函數方法參數中設置類變量嗎?
的僞代碼
public class Employee {
String first_name;
String last_name; // can this be set automatically from the parameter of the constructor function without having to explicitly set it?
public Employee (String firstName, String lastName) {
first_name = firstName; // is there a way to avoid having to type this?
last_name = lastName;
}
}
是的。你可以在構造函數中初始化類的變量。 – 2012-02-02 23:06:32
否(至少,沒有反射,我認爲這不是一個選項)。至多,您可以在字段聲明中提供默認值('String first_name =「John」;'),但是您需要以某種方式指示JVM如何將值分配給字段(您可能想要交換ctor參數,對吧?) – 2012-02-02 23:07:58
@RaviG:AFAIU,問題是自動將ctor參數值複製到對象字段中(根據代碼中的註釋。 ) – 2012-02-02 23:09:33