Saturday 14 June 2014

When initialization occurs in an interface?


    • According to Java language specification, initialization of an interface consists of executing the initializers for fields declared in the interface. Before a class is initialized, its direct superclass must be initialized.
    • But interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized. Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.
    • Following is example for this :
    • The reference to J.i is to a field that is a compile-time constant; therefore, it does not cause I to be initialized. The reference to K.j is a reference to a field actually declared in interface J that is not a compile-time constant; this causes initialization of the fields of interface J, but not those of its superinterface I, nor those of interface K. Despite the fact that the name K is used to refer to field j of interface J, interface K is not initialized.
    • System.out.println(J.i); // The i variable is inherited from I but since it is a constant - you don't have to go through the whole process of initializing I, just reference it and get on with things.
    • System.out.println(K.j); // now this is more complicated. Since the variable holds something other than a constant, the first thing that we have to do is initialize J so that we can figure out what to DO to come up with the value of j.
    • Initializing interface J causes variable j to be initialized first: executing Test.out("j",3) which prints j=3, and setting the variable j to 3 (note the return type on the method). Now jj is initialized executing Test.out("jj",4) which prints jj=4 and sets the variable jj to 4.
    • Now that initialization is done we can evaluate and execute the println for K.j which prints the current value of j which is 3.

      No comments:

      Post a Comment