Java 实例变量在两个语句中声明和初始化
我在 java 中的初始化有问题,下面的代码给了我编译错误,叫做:expected instanceInt = 100;但我已经宣布了.如果这些事情与堆栈和堆有关,请用简单的术语解释,我是 java 新手,我对这些领域没有高级知识
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;
}
}
推荐答案
你不能在课堂中间使用语句.它必须在一个块中或与您的声明在同一行中.
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 :
声明期间的初始化
public class MyClass{
private int i = 0;
}
如果您想为您的字段定义默认值,通常是个好主意.
Usually it's a good idea if you want to define the default value for your field.
构造函数块中的初始化
public class MyClass{
private int i;
public MyClass(){
this.i = 0;
}
}
如果您希望在字段初始化期间有一些逻辑(如果/循环),则可以使用此块.问题在于,您的构造函数要么会相互调用,要么它们的内容基本相同.
在你的情况下,我认为这是最好的方法.
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.
方法块中的初始化
public class MyClass{
private int i;
public void setI(int i){
this.i = i;
}
}
这并不是真正的初始化,但您可以随时设置您的值.
It's not really an initialization but you can set your value whenever you want.
实例初始化块中的初始化
public class MyClass{
private int i;
{
i = 0;
}
}
这种方式在构造函数不够用时使用(见构造函数块的注释),但通常开发人员倾向于避免这种形式.
This way is used when the constructor isn't enough (see comments on the constructor block) but usually developers tend to avoid this form.
资源:
- JLS - 实例初始化器
关于同一主题:
- Java 中初始化器与构造器的使用
- 实例初始化器与构造器有何不同?
奖金:
这段代码是什么?
public class MyClass {
public MyClass() {
System.out.println("1 - Constructor with no parameters");
}
{
System.out.println("2 - Initializer block");
}
public MyClass(int i) {
this();
System.out.println("3 - Constructor with parameters");
}
static {
System.out.println("4 - Static initalizer block");
}
public static void main(String... args) {
System.out.println("5 - Main method");
new MyClass(0);
}
}
答案
相关文章