當您實例化一個類時,您必須實際聲明類類型的New對象。這是通過使用new
關鍵字完成的。請參閱下面的示例,使用您的代碼!另外,在這個例子中不需要外部類。
public final class Immutable {
private String one; //For Immutable classes the variables must be declared as private so their values are not modified outside the class.
private String two;
public static void main(String[] args) {
// Do I instantiate my class here?
Immutable immutableObject = new Immutable(); // We just created an instance of the class
}
}
請記住,而Java的確提供了內置的默認構造函數,這是很好的做法,創建自己的構造函數。例如
public final class Immutable {
private String one;
private String two; //Must be private, it is also good to protect your variables
// This is a default constructor
Immutable() {
one = "default value";
two = "default value";
}
// Parameter-accepting constructor
Immutable (String one, String two) {
this.one = one;
this.two = two;
}
public static void main(String[] args) {
// Do I instantiate my class here?
Immutable immutableObject = new Immutable(); // Default
Immutable immutableObject2 = new Immutable ("A string", "Another string"); // Now we defined the Strings in the instance!
}
} // End class
通過建立我們自己的構造函數,我們可以可以肯定的是我們的類定義正是我們預期的方式。
你想知道類是如何裝? – User27854 2015-02-06 02:00:15
[Immutable class?]可能的重複(http://stackoverflow.com/questions/3162665/immutable-class) – User27854 2015-02-06 02:17:17