0

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

1
  • 2
    Could you add some code to describe precisely what you mean? And "which one is the best one to use" - this is too general to be answered. Is a screwdriver or a hammer the best to use? Commented Sep 24, 2010 at 8:20

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.