+ 1
Help me understand static variables
https://code.sololearn.com/cHYG205ljfd5/?ref=app Here I declared two classes, one with static variable and the other with non-static variable. When I call and display the values of each variable, why does count from Sydney class display the same value 2 each time. And next when time from Perth class is called, why does it also display the same output but rather 1 here? If static variable is not used, isn't it supoosed to be 1 and then 2 in successive lines? Why does it print the same value 1 on each call. Can someone please explain the logic behind this output.
3 Answers
+ 2
Verstappen
Because static variable stores in memory so when you have created 2 object of Sydney class, then count increased so now count is 2 which is stored in memory.
So now both objects of Sydney class will share same memory. Doesn't matter how many time you are printing count, every time same value will be print.
For the second case each object just incrementing count once because of non-static variable.
+ 1
This might help you ,
https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.tutorialspoint.com/Static-variables-in-Java%23:~:text%3DClass%2520variables%2520also%2520known%2520as,objects%2520are%2520created%2520from%2520it.%26text%3DStatic%2520variables%2520are%2520stored%2520in%2520the%2520static%2520memory.&ved=2ahUKEwjhi7KAlqHyAhUbU30KHXZCDGAQFnoECAMQBQ&usg=AOvVaw3FgbRyL4Ipk9t9-sNntOBn&cshid=1628416991735
+ 1
A͢J - SÍoÍlÍoÍHÍeÍlÍpÍeÍrÍ oh thanks, this makes things clearer now đ