Java中方法内的最终变量 [英] Final variables inside a method in Java

查看:503
本文介绍了Java中方法内的最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,最终变量只需初始化一次。不允许其他初始化。如果是这样的话,当在方法内声明最终变量时会发生什么。假设在其中声明最终变量的方法被调用/调用三次,方法中该最终变量的声明语句被执行三次,并且最终变量应该被初始化三次,这在特定的Java中是非法的。在这种情况下,编译器如何在方法中维护最终变量?

As a rule, a final variable has to be initialized only once. No other initializations are permitted. If it is so then, what happens when a final variable is declared inside a method. Suppose the method which a final variable is declared within is invoked/called thrice, the declaration statement of that final variable within the method is executed thrice and the final variable should be initialized thrice which is illegal specifically in Java by convention. In such a scenario, how could the compiler maintain the final variable inside a method?

推荐答案

局部变量仅在范围内方法的持续时间。可以为每个方法范围初始化一次变量。

The local variable is only in scope for the duration of the method. The variable can be initialized once for each method scope.

您可能希望读取堆栈与堆,以了解JVM如何保存方法的数据。

You might want to read up on the stack vs the heap to learn about how the JVM holds data for a method.

这篇关于Java中方法内的最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆