tags:

views:

52

answers:

1

Hi, 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

+2  A: 

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.

Faisal Feroz
Thanks Faisal! I have a scenario like I have a static method to develop user interface ,in which I created Button and performing corresponding action using Listener interface.So,in this case I want to know whether I want to have button as final and create button using new object inside the method in which I use, or is it better to have button as static Variable outside the method as I am using static method.Which one will be better approach and how it will the effective.
Android_programmer_camera
If you don't want to reference to your button anywhere else in your program then final inside the method is the way to go. Static variables are a lot like Global Variables and should be avoided (not an OOP principle) wherever possible to have a good design of the product.
Faisal Feroz
Thanks a lot. I understood it well.
Android_programmer_camera