+ 3

I got this question in a challenge, but couldn't figure out how the output "00" was achieved. Please explain if you can...

https://www.sololearn.com/post/479261/?ref=app

29th Jul 2020, 7:56 AM
Bukunmi Ola
Bukunmi Ola - avatar
7 Answers
+ 2
Woow wow wow..... Lakshay Mittal and ŠœŠ³. ŠšŠ½Š°ŠæšŸŒ  The answers were on point. Thanks šŸ™ŒšŸ½
29th Jul 2020, 9:14 AM
Bukunmi Ola
Bukunmi Ola - avatar
+ 1
Oh yeah... Now I got it, the foo doesn't affect obj The programme just printed the default value of i. So how do we validly call foo() ?
29th Jul 2020, 8:18 AM
Bukunmi Ola
Bukunmi Ola - avatar
+ 1
Actually, fooA and fooB will affect the obj. I didn't notice that main() is inside same class 'Program'.
29th Jul 2020, 8:40 AM
Lakshay Mittal
Lakshay Mittal - avatar
+ 1
Really? Why is foo(obj) still zero then?
29th Jul 2020, 8:59 AM
Bukunmi Ola
Bukunmi Ola - avatar
+ 1
Initial value of 'i' variable of both class A and B in 'obj' is 0 as assigned by constructor of both classes. Now, when fooA() is called it alters the Class A's 'i' in obj to 3 but when 'obj.i' is displayed, it meant Class B's 'i' which is still 0. Now, when fooB() is called the if condition is not met and Class B's 'i' stays 0 even when it meant Class B's 'i' and when 'obj.i' is displayed it again outputs 0. Hope you Understand!
29th Jul 2020, 9:07 AM
Lakshay Mittal
Lakshay Mittal - avatar
+ 1
Bukunmi Ola As far as my understanding goes, the instance variable (here, i) cannot be overridden .. which means when you passed the obj object of class B into fooA(A a) method it cannot change the variable of A class.. BUT add print statment in the fooA() method after a.i = 3; And print the (a.i) you will get 3 because the 'A a' here is the reference variable of the A class so it can override its own variables. and when the statment (obj.i) is printed after the fooA(obj) statement.. the obj.i looked for it's instance variable i, which didn't had any value so it printed 0.. And for the second case fooB(obj) on printing (obj.i) the if statement is False therefore it couldn't change the Value of i to 5.. and it results to 0. if you Comment the If statement line Then you will get the output as 5.. AND, since fooA and fooB are static methods defined in Program class where the main method is present, so we can access the static methods in the main method directly without creating any object of Program class
29th Jul 2020, 9:07 AM
ŠœŠ³. ŠšŠ½Š°ŠæšŸŒ 
ŠœŠ³. ŠšŠ½Š°ŠæšŸŒ  - avatar
29th Jul 2020, 9:22 AM
TheAdeyemiOlayinka šŸ’—
TheAdeyemiOlayinka šŸ’— - avatar