为什么Final变量不需要在java中的main方法初始化? [英] Why Final variable doesn't require initialization in main method in java?

查看:120
本文介绍了为什么Final变量不需要在java中的main方法初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我只是想在 Java 中做一些程序时。我尝试使用 final 变量,我知道 final 变量必须在声明时初始化,但在main方法中它接受 final 变量而不进行初始化。我不知道是什么原因。任何人都可以告诉我原因。

When I am just trying to do some program in Java.I try to use final variable,I know that final variable must be initialized at the time of declaration, but inside the main method it accepts the final variable with out initialization. I don't know what's the reason.Can any one tell me the reason.

谢谢

代码:

class name
{
     final int b; //here shows error
     public static void main(String args[])
    {
        final int a; // here no error... why?
        System.out.println("hai");
    }
}


推荐答案

实例变量级别


  • 最终变量只能初始化一次。

  • A final variable can be initialized only once.

类级别的最终变量必须在构造函数结束之前初始化

A final variable at class level must be initialized before the end of the constructor.

本地(方法)级别


  • 最终变量在方法级别只能初始化一次。

  • 必须在使用之前初始化

  • A final variable at method level can be initialized only once.
  • It must be initialized before it is used

所以基本上如果你不使用本地最终变量,你也可以跳过它的初始化。

So basically if you don't use a local final variable you can also skip it's initialization.

如果变量是实例级别你必须在定义或costructor体中初始化它。

If the variable is at instance level you have to initialize it in the definition or in the costructor body.

在你的代码中你有一个实例变量 final int b 从未初始化,因此您有错误。

In your code you have an instance variable final int b that is never initialized so you have an error.

您还有一个本地变量 final int a 从未使用过。所以你没有该变量的错误。

You have also a local variable final int a that is never used. So you haven't an error for that variable.

这篇关于为什么Final变量不需要在java中的main方法初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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