在Java中,要区分一下类和对象。对象必须基于类创建,但是不创建对象,也可以使用类中的某些成员和方法(如static修饰的)。因此,Java的初始化应该包括Class Initialization和Object Initialization。

初始化的重要性

Initialization is important because, historically, uninitialized data has been a common source of bugs. //不初始化,由于值不确定,很有可能出现bug
Bugs caused by uninitialized data occur regularly in C, for example, because it doesn't have built-in mechanisms to enforce proper initialization of data. C programmers must always remember to initialize data after they allocate it and before they use it. //C语言躺枪。。。。。
The Java language, by contrast, has built-in mechanisms that help you ensure proper initialization of the memory occupied by a newly-created object. //还是Java为程序员着想

一般情况下,JVM会帮我们把所有的变量进行初始化。我们需要了解的只是初始化的默认值和初始化的顺序。

Initializing classes

Class Initialization通常是指static成员的初始化。

默认值

class SomeClass
{
static boolean b;
static byte by;
static char c;
static double d;
static float f;
static int i;
static long l;
static short s;
static String st;
}

上面的class中声明了一些static对象,但是并没有明确指定值。这种情况下,当SomeClass被装载的时候,里面的对象会都被赋值默认值,分别为:

false //boolean默认值。

0 //byte默认值

\u0000 //char默认值

0.0 //double默认值

0.0 //float默认值

0 //int默认值

0 //long默认值

0 //short默认值

null //String默认值。引用类型默认值都为null

注意:int, long, boolean的包装类型分别为Integer, Long, Boolean,属于非基本类型。非基本类型都会被赋予默认值null。

显式赋值

class SomeClass
{
static boolean b = true;
static byte by = 1;
static char c = 'A';
static double d = 2.0;
static float f = 3.0f;
static int i = 4;
static long l = 5000000000L;
static short s = 20000;
static String st = "abc";
}

这个很简单,人为指定是啥值就是啥值。不过这种情况下,初始化会进行两次。以int i=4为例,首先i会被初始化为0,这是第一次初始化。然后i会被赋值为4,这是第二次初始化。

static块(static block)始化
class Graphics
{
static double[] sines, cosines;
static
{
sines = new double[360];
cosines = new double[360];
for (int i = 0; i < sines.length; i++)
{
sines[i] = Math.sin(Math.toRadians(i));
cosines[i] = Math.cos(Math.toRadians(i));
}
}
}

类的static变量可以在static包围的块中进行初始化。这样做的好处是能带来微小的性能呢过提升。以上面的例子做为解释,sines和cosines都是个数组,直接从数组中取值速度很快。如果不这样做,而是每次调用都重新赋值,会多次调用Math.sin()和Math.cos()函数,这样效率很不好。

Initializing objects

构造函数初始化

通常呢,对象的初始化会在构造函数中进行:

class City
{
private String name;
int population;
City(String name, int population)
{
this.name = name;
this.population = population;
}
@Override
public String toString()
{
return name + ": " + population;
}
public static void main(String[] args)
{
City newYork = new City("New York", 8491079);
System.out.println(newYork); // Output: New York: 8491079
}
}

默认初始化

但是,如果不在构造函数中初始化,每个变量有会有个默认的值。JVM为不同类型的变量赋予的默认值同static变量默认赋值。

class City
{
private String name; //默认初始化为null
int population; //默认初始化为0
City(String name, int population){
this.name = name;
this.population = population;
}

显示初始化

当然,变量也可以显示指定值。

class City
{
private String name;
int population;
int numDoors = 4; // 显示初始化
Car(String make, String model, int year){
this(make, model, year, numDoors);
}
Car(String make, String model, int year, int numDoors){
this.make = make;
this.model = model;
this.year = year;
this.numDoors = numDoors;
}

Java类/对象的初始化顺序

类初始化

类初始化的顺序比较简单,只需要遵从一个原则:

从上到下顺序执行

如下代码,先执行x=2赋值,再执行y=x

class SomeClass
{
static int x = 2;
static int y = x;
public static void main(String[] args)
{
System.out.println(x);
System.out.println(y);
}
}

既然顺序执行,就需要注意编码时成员的顺序。如下代码就会报illegal forward reference这样的错误。这是因为编译器从上到下编译的时候,y还没找到声明就赋值给x,这是不允许的。

class SomeClass
{
static int x = y;
static int y = 2;
public static void main(String[] args)
{
System.out.println(x);
System.out.println(y);
}
}

引申

Java编译器会将static成员和static块编译后的代码放到()方法中,JVM会在main()函数(如果这个类中有main方法)调用之前调用()方法。

对象初始化

对于对象的初始化,需要遵从以下几个原则:

如果有static代码,最先执行。如果有父类,先执行父类static代码,再执行子类static代码。

如果有父类,执行父类非static代码

如果有父类,执行父类构造函数

执行子类非static代码

最后执行子类构造函数

主要思想

static优先(当然,父类中的static更优先)。static只执行一次

父类次之

构造函数最后

下面是两个例子:

image.png

image.png

注意

image.png

对于父类初始化,子类默认调用父类的无参构造函数。如果构造函数中显式调用父类的其他构造函数,父类的初始化也是优先进行。

引申

Java编译器会生成一个()(叫instance initialization method)代替构造函数。JVM调用的不是对象的构造函数,而是()方法。

如:

class CoffeeCup {
public CoffeeCup() {
//...
}
public CoffeeCup(int amount) {
//...
}
// ...
}

上面的两个构造函数会被编译成如下两个instance initialization methods函数:

// In binary form in file init/ex8/CoffeeCup.class:
public void (CoffeeCup this) {...}
public void (CoffeeCup this, int amount) {...}
When a class doesn't extend another class, the () method begins with bytecode to call the Object() constructor. When a constructor starts with super(), () begins with bytecode to call the superclass constructor. When a constructor begins with this() (to call another constructor in the same class), () begins with the bytecode sequence for calling the other constructor; it doesn't contain code to call a superclass constructor.