在Java中,类变量的初始化可以通过以下几种方式:
public class MyClass {
static int myStaticVar = 10; // 静态变量
int myInstanceVar = 20; // 实例变量
}
public class MyClass {
static int myStaticVar;
int myInstanceVar;
public MyClass() {
myStaticVar = 10;
myInstanceVar = 20;
}
}
public class MyClass {
static int myStaticVar;
static {
myStaticVar = 10;
}
int myInstanceVar;
}
public class MyClass {
static int myStaticVar;
int myInstanceVar;
{
myInstanceVar = 20;
}
}
public class MyClass {
static int myStaticVar;
int myInstanceVar;
public void setMyInstanceVar(int value) {
myInstanceVar = value;
}
}
请注意,静态变量属于类,因此它们在类加载时初始化。实例变量属于对象实例,因此它们在创建对象时初始化。