發新話題

Java 教程《語法說明》Constructor Implementation

Java 教程《語法說明》Constructor Implementation

■ Constructor Implementation
[class-modifiers] class ClassName {
  [access-modifiers]  ClassName throws checked-exceptions( [parameterList] ) {
    //constructor-implementation
    ‥‥
  }
  ‥‥
}

[說明]
1. 定義建構子(constructor)。建構子用以初始化新建立的物件。
2. constructor 的名稱必須和其所屬的類別名稱相同。
3. constructor不能指定任何傳回值型態或傳回任何值。
4. 當建立某個 class 的物件時,會自動呼叫建構子(constructor)。
5. constructor可被overloaded,以提供多種的物件初始化情況。
6. 建構子並不是method。
7. constructor內若使用 this( ) 或 super( ) 呼叫建構子,則不允許補抓由 constructor 丟出的exception。
 因物件在使用前必須保證被正確的初始化,而且 super( ) 和 this( ) 必須出現在建構式內的第一行。
8. constructor不能宣告為 abstract、static、final、native、strictfp、或 synchronized。衍生類別不會繼承建構子。
9. class 內若沒定義任何的建構子,則編一時會自動產生一個沒有帶任何參數,不做任何動作的default建構子。
 default constructor 與該 class 有相同的 access modifier。

[範例]
public class A {
  ‥‥
  public A(int initialValue) {
    balance = initialValue;
  }
  ‥‥
}

[範例]
class Outer {
  class Inner{ }
}
class ChildOfInner extends Outer.Inner {
  ChildOfInner( ) { (new Outer( )).super( ); }
}

[範例] JLS 2.0
If an anonymous class instance creation expression appears within an explicit constructor invocation statement,
then the anonymous class may not refer to any of the enclosing instances of the class whose constructor is being invoked.

class Test {
  int myVar;
  class InnerClass1 {
    InnerClass1(Object o) {  }
  }
  class InnerClass2 extends InnerClass1 {
    InnerClass2( ) {
      super( new Object( ) { int r = myVar; } );  // error
    }
    InnerClass2(final int myConst) {
      super( new Object( ) { int r = myConst; } );  // correct
    }
  }
}

[範例]
package p1;
public class Outer {
  protected class Inner {  }
}

package p2;
class SonOfOuter extends p1.Outer {
  void foo( ) {
    new Inner( );  // compile-time access error
  }
}

內部類別 Inner 的 constructor 為 protected 權限,但是該 constructor 相對於 Inner 為 protected 權限。
SonOfOuter 類別是 Outer 的衍生類別,可以存取 Inner,但是 SonOfOuter 內不能存取 Inner 的 default constructor,因為 SonOfOuter 類別不是 Inner 的衍生類別。

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。