为什么我不能在方法之外进行赋值? [英] Why can't I do assignment outside a method?

查看:30
本文介绍了为什么我不能在方法之外进行赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试为类中的变量赋值,但在方法之外我得到一个错误.

If I try to assign a value to a variable in a class, but outside a method I get an error.

class one{
 Integer b;
 b=Integer.valueOf(2);
}

但是,如果我在创建过程中初始化它,它就可以工作.

but, if I initialize it during the creation, it works.

class one{
 Integer b=Integer.valueOf(2);
}

在一个方法中,它适用于两种情况.

Inside a method, it works in both cases.

推荐答案

你需要做的

class one{
 Integer b;
 {
    b=Integer.valueOf(2);
 }
}

as 语句必须出现在代码块中.

as statements have to appear in a block of code.

在这种情况下,块是一个初始化块,它被添加到每个构造函数(或在这种情况下的默认构造函数)它在对 super() 的任何调用之后和主块之前运行任何构造函数中的代码.

In this case, the block is an initailiser block which is added to every constructor (or the default constructor in this case) It is run after any call to super() and before the main block of code in any constructor.

顺便说一句:你可以有一个带有 static { } 的静态初始化块,它在类初始化时被调用.

BTW: You can have a static initialiser block with static { } which is called when the class is initialised.

例如

class one{
 static final Integer b;

 static {
    b=Integer.valueOf(2);
 }
}

这篇关于为什么我不能在方法之外进行赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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