在Java中,要區(qū)分一下類和對(duì)象。對(duì)象必須基于類創(chuàng)建,但是不創(chuàng)建對(duì)象,也可以使用類中的某些成員和方法(如static修飾的)。因此,Java的初始化應(yīng)該包括Class Initialization和Object Initialization。
初始化的重要性
Initialization is important because, historically, uninitialized data has been a common source of bugs. //不初始化,由于值不確定,很有可能出現(xiàn)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語(yǔ)言躺槍。。。。。
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會(huì)幫我們把所有的變量進(jìn)行初始化。我們需要了解的只是初始化的默認(rèn)值和初始化的順序。
Initializing classes
Class Initialization通常是指static成員的初始化。
- 默認(rèn)值
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對(duì)象,但是并沒有明確指定值。這種情況下,當(dāng)SomeClass
被裝載的時(shí)候,里面的對(duì)象會(huì)都被賦值默認(rèn)值,分別為:
false //boolean默認(rèn)值。
0 //byte默認(rèn)值
\u0000 //char默認(rèn)值
0.0 //double默認(rèn)值
0.0 //float默認(rèn)值
0 //int默認(rèn)值
0 //long默認(rèn)值
0 //short默認(rèn)值
null //String默認(rèn)值。引用類型默認(rèn)值都為null
注意:int, long, boolean的包裝類型分別為Integer, Long, Boolean,屬于非基本類型。非基本類型都會(huì)被賦予默認(rèn)值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";
}
這個(gè)很簡(jiǎn)單,人為指定是啥值就是啥值。不過這種情況下,初始化會(huì)進(jìn)行兩次。以int i=4
為例,首先i
會(huì)被初始化為0,這是第一次初始化。然后i
會(huì)被賦值為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包圍的塊中進(jìn)行初始化。這樣做的好處是能帶來微小的性能呢過提升。以上面的例子做為解釋,sines和cosines都是個(gè)數(shù)組,直接從數(shù)組中取值速度很快。如果不這樣做,而是每次調(diào)用都重新賦值,會(huì)多次調(diào)用Math.sin()和Math.cos()函數(shù),這樣效率很不好。
Initializing objects
- 構(gòu)造函數(shù)初始化
通常呢,對(duì)象的初始化會(huì)在構(gòu)造函數(shù)中進(jìn)行:
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
}
}
- 默認(rèn)初始化
但是,如果不在構(gòu)造函數(shù)中初始化,每個(gè)變量有會(huì)有個(gè)默認(rèn)的值。JVM為不同類型的變量賦予的默認(rèn)值同static變量默認(rèn)賦值。
class City
{
private String name; //默認(rèn)初始化為null
int population; //默認(rèn)初始化為0
City(String name, int population){
this.name = name;
this.population = population;
}
- 顯示初始化
當(dāng)然,變量也可以顯示指定值。
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類/對(duì)象的初始化順序
類初始化
類初始化的順序比較簡(jiǎn)單,只需要遵從一個(gè)原則:
從上到下順序執(zhí)行
如下代碼,先執(zhí)行x=2
賦值,再執(zhí)行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);
}
}
既然順序執(zhí)行,就需要注意編碼時(shí)成員的順序。如下代碼就會(huì)報(bào)illegal forward reference
這樣的錯(cuò)誤。這是因?yàn)榫幾g器從上到下編譯的時(shí)候,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編譯器會(huì)將static成員和static塊編譯后的代碼放到<cinit>()
方法中,JVM會(huì)在main()
函數(shù)(如果這個(gè)類中有main方法)調(diào)用之前調(diào)用<cinit>()
方法。
對(duì)象初始化
對(duì)于對(duì)象的初始化,需要遵從以下幾個(gè)原則:
- 如果有static代碼,最先執(zhí)行。如果有父類,先執(zhí)行父類static代碼,再執(zhí)行子類static代碼。
- 如果有父類,執(zhí)行父類非static代碼
- 如果有父類,執(zhí)行父類構(gòu)造函數(shù)
- 執(zhí)行子類非static代碼
- 最后執(zhí)行子類構(gòu)造函數(shù)
主要思想
- static優(yōu)先(當(dāng)然,父類中的static更優(yōu)先)。static只執(zhí)行一次
- 父類次之
- 構(gòu)造函數(shù)最后
下面是兩個(gè)例子:
注意
對(duì)于父類初始化,子類默認(rèn)調(diào)用父類的無參構(gòu)造函數(shù)。如果構(gòu)造函數(shù)中顯式調(diào)用父類的其他構(gòu)造函數(shù),父類的初始化也是優(yōu)先進(jìn)行。
引申
Java編譯器會(huì)生成一個(gè)<init>()
(叫instance initialization method)代替構(gòu)造函數(shù)。JVM調(diào)用的不是對(duì)象的構(gòu)造函數(shù),而是<init>()
方法。
如:
class CoffeeCup {
public CoffeeCup() {
//...
}
public CoffeeCup(int amount) {
//...
}
// ...
}
上面的兩個(gè)構(gòu)造函數(shù)會(huì)被編譯成如下兩個(gè)instance initialization methods函數(shù):
// In binary form in file init/ex8/CoffeeCup.class:
public void <init>(CoffeeCup this) {...}
public void <init>(CoffeeCup this, int amount) {...}
When a class doesn't extend another class, the <init>() method begins with bytecode to call the Object() constructor. When a constructor starts with super(), <init>() begins with bytecode to call the superclass constructor. When a constructor begins with this() (to call another constructor in the same class), <init>() begins with the bytecode sequence for calling the other constructor; it doesn't contain code to call a superclass constructor.