why this output in java

sinsen526 :

I have following java code segment,

class A{
    int a=100;
    A(){
        //Compiler inserts "a=100;"
        System.out.println("A() : "+a);
    }
    A(int i){
        //Compiler inserts "a=100;"
        System.out.println("A(int) : "+a);
        a=i;
    }
}
class Demo{
    public static void main(String args[]){
        A a1=new A();
        System.out.println("a1.a : "+a1.a);  //100

        A a2=new A(200);
        System.out.println("a2.a : "+a2.a);  //200
    }
}

I have following outputs with this codes

A<> :100
a1.a :100
A<> :100 //why this print after a1.a :100
a1.a :200

I have following problem. why this is a1.a :100 printing befour A<> :100?

Samuel Silver Moos :

Assuming your Example is equivalent to you Post and Output is

A() : 100
a1.a : 100
A(int) : 100
a2.a : 200

It's because your constructor in A first prints out a, and then changes value of a to i:

class A {
int a = 100;

A() {
    // a is containing it's initial value (100)
    System.out.println("A() : " + a);

}

A(int i) {
    // a is containing its initial value (100)
    System.out.println("A(int) : " + a);
    a = i;
    //a is containing now its new value (i or in your example 200)
}

If you want to have an output like

A() : 100
a1.a : 100
A(int) : 200
a2.a : 200

you have to change your Code to:

A(int i) {
    // a is containing its initial value (100)
    a = i;
    //a is containing now its new value (i or in your example 200)
    System.out.println("A(int) : " + a);
}

This is because Java first constructs your Objects Variables based on its definition, and then runs the Code of the Constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19142&siteId=1