最终变量和静态变量在内部类中的使用之间的区别
这是关于内部类中的final变量,但是如果我们在方法外部将变量声明为static,则假设该方法是静态的,而不是将变量声明为final。那么在内部类中声明为静态外部方法或最终内部方法有什么区别呢?它们会产生任何差异还是它们的功能相似。哪一种是最好使用的。我会等待回复。
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态变量将在内部类的不同实例化中保持其值。 它的 A 值将为 2。
假设您在内部类 A 中声明了一个静态变量,并为其分配了值 1,然后在方法调用中将其值增加到 2。当创建此内部类的另一个实例时, 对于最终变量,您只能在声明时赋值一次(在您的情况下,即在方法内部声明)。因此,编译器所做的就是内联该值,即无论您在何处使用该变量,该变量都会被其值替换(因为您无法更改其值)。
我建议尽可能使用最终变量。但静态有其自身的需求,并且使用取决于使用场景。
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.
Final 变量是实例变量,其值在初始化后(无论是在编译器中还是在声明时)都不能更改。
但静态变量属于一个类。这将在所有实例之间共享。因此,当您更改实例中静态变量的值时,它会反映在所有实例中。
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.