posted 13 years ago
Hello,
When you say and write this statement
Foo myBar = new Foo();
This is not written anywhere. Actually it
Now let me explain the working of code to you.
1- There is a class Bar having an instance variable myBar.
2- There is a class Foo which has an instance variable of type Bar and it is instantiated to Bar myBar = new Bar()
3- Class Foo as a changeIt() method and a main Method.
Now the flow of program goes like this
1- When you say Foo f = new Foo(), an object of type foo is intantiated.
2- Next the code wants to access the instance variable of class Bar whcih is barNum. The way to get that instance variable in Foo class is
using its own instance variable myBar. So it would be
At this point two objects are present, one object of type Foo and that foo internally has the Bar class object.
Now this statement executes
Now here, two reference variables are pointing towards the Bar object. As the instance variable and the method local variable
as the same name which is myBar, the instance variable is shadowed by method local variable myBar. Now as both of the reference
variables are pointing towards same bar object when inside changeIt() method, this statement excutes
The state of the object changes and now the value of barNum is going to be 99 when it is printed out.
Now when the above statement executes, a new object is created and now the method local reference variable myBar
is pointing towards the new object of Bar class. Lets look ahead when we execute this part
The method local reference variable changes the value of barNum to 420 and it is printed out. Remember that, it won't
effect the value of barNum of the instance variable. After this point changeIt() completes and the object goes out of scope
as it was only local to the method.
Now the statement in main will execute
I cannot understand third point you mentioned. Because there is no other object of type Foo is created, the local reference variable
is pointed towards a new object of Bar class and that object is local to the method and Bar and Foo don't share it.
Hope it helps.
Best Regards,