第五章 初始化与清理
一、初始化
1、构造器 constructor
2、方法重载:不同构造器,参数列表独一无二
3、默认构造器(无参)
-
创建默认对象
-
this 关键字
- 表:对调用方法的按个对象的应用
- 若为同一个类的另一个方法,不使用 this 关键字,精简
- 若要明确指出对当前对象的引用,使用 this 关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class Apricot{ void pick(); void pit{ pick() }; void pit{ this.pick() }; }
public class Leaf{ int i = 0; Leaf increment() { i++; return this; } } void print() { System.out.println("i = " + i); } public static void main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment().print(); }
|
4、成员初始化
5、构造器初始化
1 2 3 4 5 6 7 8
| public class Counter { int i; Counter() { i = 7; } ... }
|
-
初始化将在构造器被调用前发生
-
类内部,变量定义顺序决定了初始化顺序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Window { Window(int marker) { print("Windows(" + marker + ")"); } } class House { Window w1 = new Window(1); House() { print("House()"); w3 = new Window(33); } Window w2 = new Window(2); void finished() { print("finished()"); } Window w3 = new Window(3); } public class OrderOfInitialization { public static void main(String[] args) { House h = new House(); h.finished(); } }
|
上例说明,即使对象散布在 Window 的不同部分,仍会在调用构造器或其他方法前得到初始化。
-
先初始化静态对象,后其他对象
-
静态块:显式的静态初始化
1 2 3 4 5
| static { 代码块1 代码块2 ... }
|
静态初始化动作只进行一次
6、数组的初始化
以下两种均可(前者更合理,后者符合 C、C++ 习惯):
1 2 3 4 5 6 7 8
| int[] a; int a[];
int[] a = new int[rand.nextInt(20)];
import java.util.*; print(Arrays.toString(a));
|
-
不允许指定数组的大小,分配空间必须写初始化表达式
-
使用花括号括起来的列表初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| ... Interger[] a = { new Interger(1), new Interger(2), 3, }; public class DynamicArray { public static void main(String[] args) { Other.main(new String[]){ "fiddle", "de", "dum"}; } } class Other { public static void main(String[] args) { for(String s : args) System.out.print(s + " "); } }
|
7、可变参数列表
二、清理
1、finalize ():清理不是 new 创建的内存
2、辨析:并非所有对象都会被垃圾回收
3、回收
三、枚举类型 enum
1、toString
2、ordinal:用于表示特定枚举常量的声明顺序
3、可把 enum 视作类,具有自己的方法