If the following change is made,
Test p1 = new Test();
p1.foo()
Test p2 = p1;
p2.foo();
the print result changes from 10 10 to 5 5. p2.foo() call behavior has changed.
I'm blanking out as to why!
About Question enthuware.ocajp.i.v8.2.1425 :
Moderator: admin
-
- Posts: 221
- Joined: Mon Nov 26, 2018 2:43 pm
- Contact:
-
- Site Admin
- Posts: 10095
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1425 :
Well, you just need to follow the code line by line. If you use the same instance of Test, the while loop will never execute in the second call to foo.
Put a couple of print statements and run the code so see the value of variables.
Put a couple of print statements and run the code so see the value of variables.
If you like our products and services, please help us by posting your review here.
-
- Posts: 221
- Joined: Mon Nov 26, 2018 2:43 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1425 :
I think it was momentry inasanity not blanking out. After the first call, b = 0 and without staring a new instance it stays 0
-
- Posts: 4
- Joined: Wed Nov 22, 2023 1:59 am
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1425 :
Hi,
I still don't understand the result. I've read the explanation :..."when you call p1.foo() and then p2.foo(), the same field a is incremented 5 times twice and so it will print 10 10."
ok, after the while loop a=5; when you call for example p1.a, does this mean that the while loop runs one more time and that's why a=10?
If not, what is actually happening?
Thank you,
Iulian
I still don't understand the result. I've read the explanation :..."when you call p1.foo() and then p2.foo(), the same field a is incremented 5 times twice and so it will print 10 10."
ok, after the while loop a=5; when you call for example p1.a, does this mean that the while loop runs one more time and that's why a=10?
If not, what is actually happening?
Thank you,
Iulian
-
- Site Admin
- Posts: 10095
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1425 :
No, look at the while condition. It uses b>0. b is not a static field. It is an instance field, which means there is one b in each instance of class Test. So, when you invoke p1.foo(), p1's b goes from 5 to 0 and when you invoke p2.foo(), p2's b goes from 5 to 0. But both times, the loop increment the same a because a is static. All instances of Test share the same field a. So, it's value is 5 after p1.foo(), and then 10 after p2.foo().
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 12 guests