sinsen526 :
I have following java program,
class A{
int a=100;
A(int i){
}
{
a=300;
}
void printA(){
System.out.println("a : "+a);
}
}
class Demo{
public static void main(String args[]){
A a1=new A(200);
a1.printA(); //300
}
}
but I cant understand why main method 'a1.printA(); ' as 300 can you explain some thing?
Stultuske :
class A{
A(int i){
}
int a=100;
{
a=300;
}
void printA(){
System.out.println("a : "+a);
}
}
class Demo{
public static void main(String args[]){
A a1=new A(200);
a1.printA(); //300
}
}
OK, you set the value for that instance variable two times:
int a = 100;
this is the first one to execute. So, this is where it starts.
Then, you initialize your class, so your initialize block will be executed, which contains:
a=300;
this will overwrite the previous value.
You also pass a param to your constructor, but you don't use it. So this doesn't change the value of a.