This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Monday, January 11, 2010

7 - Object Creation

Have a look at the following and predict the ouput...
A
B extends A
C extends B
creation of a C

public class A {

    static {
        System.out.println("creating and init static A");
    }
    static int staticA1 = 0;

    {
        System.out.println("creating and init instance A");
    }
    int instanceA1 = 0;

    A() {
        super();
        System.out.println("in the A constructor");
    }

    static {
        System.out.println("static bloc A");
        staticA1 = -1;
    }

    {
        System.out.println("non static bloc A");
        instanceA1 = -1;
    }
}

public class B extends A {

    static {
        System.out.println("creating and init static B");
    }
    static int staticB1 = 0;

    {
        System.out.println("creating and init instance B");
    }
    int instanceB1 = 0;

    B() {
        super();
        System.out.println("in the B constructor");
    }

    static {
        System.out.println("static bloc B");
        staticB1 = -2;
    }

    {
        System.out.println("non static bloc B");
        instanceB1 = -2;
    }
}

public class C extends B {

    public static void main(String[] args) {
        System.out.println("new C()");
        C refC = new C();
        System.out.println("staticA1:" + refC.staticA1);
        System.out.println("instanceA1:" + refC.instanceA1);
        System.out.println("staticB1:" + refC.staticB1);
        System.out.println("instanceB1:" + refC.instanceB1);
        System.out.println("staticC1:" + refC.staticC1);
        System.out.println("instanceC1:" + refC.instanceC1);
    }

    static {
        System.out.println("creating and init static C");
    }
    static int staticC1 = 0;

    {
        System.out.println("creating and init instance C");
    }
    int instanceC1 = 0;

    C() {
        super();
        System.out.println("in the C constructor");
    }

    static {
        System.out.println("static bloc C");
        staticC1 = -3;
    }

    {
        System.out.println("non static bloc C");
        instanceC1 = -3;
    }
}

run :

creating and init static A
static bloc A
creating and init static B
static bloc B
creating and init static C
static bloc C
new C()
creating and init instance A
non static bloc A
in the A constructor
creating and init instance B
non static bloc B
in the B constructor
creating and init instance C
non static bloc C
in the C constructor
staticA1:-1
instanceA1:-1
staticB1:-2
instanceB1:-2
staticC1:-3
instanceC1:-3

No comments:

Post a Comment

Followers