Resolved: Static Method accessing Static variable

In this post, we will see how to resolve Static Method accessing Static variable


Can someone explain why upon execution, inside functionZ(), y is printed as 0 and not 30? Before z is invoked, in functionA we’ve already set the value to 30. And since there is supposed to only be one copy of a static variable across all instances of an object, shouldn’t it be 30?

Best Answer:

Inside your functionA you defining a local variable y:
While you are in that function all access to y will go into this variable, so you set it to 30. This did however not impact the static variable y, which still has the value 0 and it is accessed from the static method functionZ.
To emphasize you want to access the static variable y rather than the local variable y, use the qualified identifier Practice.y.

If you have better answer, please add a comment about this, thank you!