为什么我不能在方法之外做任务? [英] Why can't I do assignment outside a method?

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

问题描述

如果我尝试为类中的变量赋值,但在方法之外我会收到错误。

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 statements have to appear in a block of code.

在这种情况下,块是一个initailiser块,它被添加到每个构造函数(在这种情况下是默认构造函数)它在对<$ c的任何调用之后运行$ c> 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.

BTW:你可以使用静态初始化块 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天全站免登陆