Java实例变量声明和初始化在两个语句中
您好,我在 java 中初始化时遇到问题,以下代码给我编译错误,名为:expected instanceInt = 100;但我已经宣布了。如果这些事情与堆栈和堆相关,请用简单的术语解释,我是java新手,我对这些领域没有高级知识
public class Init {
int instanceInt;
instanceInt = 100;
public static void main(String[] args) {
int localInt;
u = 9000;
}
}
Hi I'm having problem with initialization in java, following code give me compile error called : expected instanceInt = 100; but already I have declared it. If these things relate with stack and heap stuff please explain with simple terms and I'm newbie to java and I have no advanced knowledge on those area
public class Init {
int instanceInt;
instanceInt = 100;
public static void main(String[] args) {
int localInt;
u = 9000;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能在课堂中间使用语句。它必须位于一个块中或与您的声明位于同一行。
执行您想要的操作的常用方法是:
声明期间的初始化
如果您想定义字段的默认值,通常这是一个好主意。
构造函数块中的初始化
如果您想在字段初始化期间有一些逻辑(if/循环),可以使用此块。它的问题是,要么你的构造函数会互相调用,要么它们都具有基本相同的内容。
对于您的情况,我认为这是最好的方法。
方法块中的初始化
这并不是真正的初始化,但您可以随时设置您的值。
实例初始化块中的初始化
当构造函数不够时使用这种方式(请参阅构造函数块上的注释),但通常开发人员倾向于避免这种形式。
资源:
关于同一主题:
奖励:
这段代码的作用是什么?
答案
You can't use statements in the middle of your class. It have to be either in a block or in the same line as your declaration.
The usual ways to do what you want are those :
The initialization during the declaration
Usually it's a good idea if you want to define the default value for your field.
The initialization in the constructor block
This block can be used if you want to have some logic (if/loops) during the initialization of your field. The problem with it is that either your constructors will call one each other, or they'll all have basically the same content.
In your case I think this is the best way to go.
The initialization in a method block
It's not really an initialization but you can set your value whenever you want.
The initialization in an instance initializer block
This way is used when the constructor isn't enough (see comments on the constructor block) but usually developers tend to avoid this form.
Resources :
On the same topic :
Bonus :
What does this code ?
The answer
将其放入初始化块中。
或者简单地在声明时进行初始化:
参考:
Put it in an initializer block.
Or simply initialize while declaring it:
References:
您不能使用单独的语句来为声明区域中的类成员赋值。您必须通过函数(通常是类方法)来执行此操作。
对于您的情况,请考虑在您宣布后立即进行作业。
You can not have a separate statement to assign values to class members in the declaration area. You have to do this from a function, typically a class method.
For your case, consider doing the assignment as soon as you declare.
您需要做的是:
如果它是静态的,您可以在静态块中初始化。
You need to do :
If it was
static
you could initialize in astatic
block.根据 Java 语言规范:
然而,该语句
不是这些东西,因此不允许它作为类主体的一部分。您需要做的是:
这是允许的,因为它是一个包含变量初始值设定项的字段声明。
According to the Java Language Specification:
However, the statement
is none of those things, therefore it is not allowed as part of a class body. What you need to do is this:
This is allowed because it is a field declaration that includes a variable initializer.