Reputation: 9329
"Can anyone explain me execution flow for the following java code ??" Sorry for my misleading statement... my question is ...
Main b = new Main();
control goes to the A class constructer, then control directly goes to the overriden method of class Main
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
Why compiler doesn't give error because x and y is not created..!! i am confused in this only.
When will x and y created in memory and when its initialization takes place ?? is the x and y created when control reaches to following statements in Main
class ?
int x = 1;
int y;
Code:
class A
{
public A() {
PrintFields();
}
public void PrintFields() {}
}
class Main extends A
{
int x = 1;
int y;
public Main() {
y = -1;
PrintFields();
}
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
}
class Test
{
public static void main(String[] args) {
Main b = new Main();
}
}
Output:
run:
x = 0 y = 0 //why 0 0 ?
x = 1 y = -1 // why 1 -1 ?
BUILD SUCCESSFUL (total time: 0 seconds)
Thank you.
Upvotes: 0
Views: 1499
Reputation: 7716
If you change:
System.out.println("x = "+x+" y = "+y);
to:
new Exception().printStackTrace(System.out); // <-- CFPMD (poor man's debugger)
System.out.println("x = "+x+" y = "+y);
This might make it easier to understand what the other answerers are telling you.
Upvotes: 0
Reputation: 234857
The flow is as follows:
main
calls new Main()
.Main()
constructor implicitly calls A()
as the first thing.A()
calls PrintFields()
. However, because this method is overridden, what actually gets executed is Main.PrintFields()
. This prints the first line x = 0 y = 0
because the x
and y
fields have default values.A()
completes, the Main()
constructor continues to execute. It initializes x
and y
. (Note that the assignment part of int x = 1;
is not executed until after A()
completes.) Main()
then calls PrintFields()
which executes again and prints the (now initialized) values of x
and y
.The description of how all this works can be found in the Java Language Specification (§12.5).
Upvotes: 3
Reputation: 19500
Main b = new Main();
control goes to the A class constructer, then calls the overriden method of class Main
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
At this time x and y have their default values
so x=0, y=0
Now control comes to
int x = 1;
int y;
public Main() {
y = -1;
PrintFields();
}
and then
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
at this time x =1 and y=-1
so output is
x=1, y=-1
Upvotes: 5