Friday 30 May 2014

Initialization of Fields in Interfaces

Every declarator in a field declaration of an interface must have a variable initializer, or a compile-time error occurs.

The initializer need not be a constant expression. It is a compile-time error if the initializer of an interface field uses the simple name of the same field or another field whose declaration occurs textually later in the same interface.

It is a compile-time error if the keyword this or the keyword super  occurs in the initializer of an interface field, unless the occurrence is within the body of an anonymous class. At run time, the initializer is evaluated and the field assignment performed exactly once, when the interface is initialized.

Note that interface fields that are constant variables  are initialized before other interface fields. This also applies to static fields that are constant variables in classes . Such fields will never be observed to have their default initial values , even by devious programs.

Example : Forward Reference to a Field
interface Test {
    float f = j;
     int j = 1;
     int k = k + 1;
}

This program causes two compile-time errors, because j is referred to in the initialization of f before j is declared, and because the initialization of k refers to k itself.

No comments:

Post a Comment