Reputation: 13369
this is regarding final variables in inner class, but instead of declaring variable as a final if we declare variable as static out side the method ,assuming that the method is static. Then what is the difference between declaring as static outside method or final inside method to be accessed in innerclass. will they make any difference or they function similarly. Which one is the best one to use. I will be waiting for reply.
Thanks in Advance
Upvotes: 0
Views: 9667
Reputation: 21
Final variables are instance variables, whose values cannot be changed after it is initialized ( either in the c'tor or while declaring ). But Static variables belongs to a class. This 'll be shared amoung all instances. So when you change the value of a static variable in an instance it gets reflected in all the instances.
Upvotes: 2
Reputation: 12785
static variables will keep their value across different instantiations of the inner class. Lets say you declare a static variable in inner class A and assign it the value 1 and then in the method call increment its value to 2. When another instance of this inner class is created it will have the value of A as 2.
In case of final variables you can assign the value only once when declaring (in your case i.e., declaring inside a method). What compiler does as a result of this is that it inlines the value i.e., wherever you this variable the variable is replaced with its value (since you cannot change its value).
I suggest using final variable wherever possible. but static has its won needs and usage depends on usage scenario.
Upvotes: 3