初始化后可以初始化静态变量吗? [英] Can i initialize static variable after the initialization?

查看:70
本文介绍了初始化后可以初始化静态变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有什么问题?

What is the problem with below code?

class test {
    static int a;
    a=10;
}

如果我是这样写的(如上所述),我会遇到编译时错误.

If I'm writing like this (as above), I'm getting a compile time error.

class test { 
    static int a=10;
    a=4;
}

第二个,我没有任何错误.

For the second one, I'm not getting any error.

推荐答案

您的所有示例都不应编译.

Neither of your examples should compile.

a=10;

是一条语句,在类声明.您只能将以下内容直接放在类中:

is a statement, which is not valid directly inside a class declaration. You can only put the following directly inside a class:

  • 成员声明(成员/静态变量声明(例如 static int a; ),方法,嵌套类和接口);
  • 静态和实例初始值设定项;
  • 构造函数.
  • Member declarations (member/static variable declarations (like static int a;), methods, nested classes and interfaces);
  • Static and instance initializers;
  • Constructors.

您需要在块内放置一条语句,例如静态初始化程序:

You need to put a statement inside a block, for example a static initializer:

static int a;

static {
  a = 10;
}

等效于:

static int a = 10;

这篇关于初始化后可以初始化静态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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