+ 3
I got this question in a challenge, but couldn't figure out how the output "00" was achieved. Please explain if you can...
7 Réponses
+ 2
Woow wow wow.....
Lakshay Mittal and Мг. Кнап🌠
The answers were on point. Thanks 🙌🏽
+ 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() ?
+ 1
Actually,
fooA and fooB will affect the obj.
I didn't notice that main() is inside same class 'Program'.
+ 1
Really? Why is foo(obj) still zero then?
+ 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!
+ 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
0
Lakshay Mittal Мг. Кнап🌠 . Yes . I see it now