当我基于我的c++知识使用Java时,我喜欢使用以下方式初始化变量。
public class ME {
private int i;
public ME() {
this.i = 100;
}
}
一段时间后,我改变了习惯
public class ME {
private int i = 100;
public ME() {
}
}
我遇到了其他人的源代码,一些使用第1公约,其他人使用第2公约。
请问你们都推荐哪个会议?为什么?
如果你在顶部或构造函数中初始化,没有太大区别,但在某些情况下,在构造函数中初始化是有意义的。
class String
{
char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
String()
{
this.arr=new char[0];
}
String(char[] arr)
{
this.arr=arr;
}
}
根据不同的情况有时你需要在顶部初始化有时在构造函数中初始化。
供参考,不使用构造函数初始化的其他选项:
class Foo
{
int i;
static int k;
//instance initializer block
{
//run's every time a new object is created
i=20;
}
//static initializer block
static{
//run's only one time when the class is loaded
k=18;
}
}