问题描述
我在 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); } }
答案