vendredi 3 juillet 2015

Query on load/link/initialise phase of java class file

Below is the code:

package packagename;

import java.lang.reflect.Method;

class Super{
    static{
        System.out.println("Super");
    }
    public void superMethod(){

    }
}

class Sub extends Super{
    static{
        System.out.println("Sub");
    }
    public void subMethod(){

    }
}

public class Example {
    public static void main(String[] args){
        Class myClass = Sub.class;
        Method[] methods = myClass.getMethods();
        for(Method eachMethod :  methods){
            System.out.println(eachMethod.getName() + " with " + eachMethod.getParameterCount() + " parameters");
        }
    }
}

On compiling this code and executing,

> java Example,

class Example gets loaded\linked\initialised. When Java interpreter starts interpreting main() method of class Example, before evaluating expression Sub.class and assign to Class myClass variable, class Super& class Sub are loaded & linked but not initialised. This is the reason static initialisation blocks of class Super & class Sub are not executed, as per below output.

In Example
subMethod with 0 parameters
superMethod with 0 parameters
wait with 0 parameters
wait with 2 parameters
wait with 1 parameters
equals with 1 parameters
toString with 0 parameters
hashCode with 0 parameters
getClass with 0 parameters
notify with 0 parameters
notifyAll with 0 parameters

Is my understanding correct on, load/link/initialise phase of class Example, Super & Sub?





Aucun commentaire:

Enregistrer un commentaire