Java 中操作對象的句柄是引用,類似 C/C++ 指針但更安全(無指針運算、自動 GC)。
String s; // 宣告引用,指向 null
s = new String(); // new 在堆上創建對象,返回引用賦給 s
s = "hello"; // 字面量直接賦值,指向常量池/堆對象
關鍵:引用未關聯對象前調用方法會拋 NullPointerException。
| 區域 | 存儲內容 | 特點 |
|---|---|---|
| 棧 | 基本型別變數、對象引用、方法幀 | 線程私有、極快、自動釋放(LIFO) |
| 堆 | 所有對象實例、數組 | 線程共享、GC 管理、分配較慢 |
| 方法區 | 類信息、常量、靜態變數、JIT 編譯代碼 | 線程共享、邏輯上屬於堆一部分 |
基本型別存棧(高頻、小尺寸),對象存堆(生命週期不確定、需 GC)。
定義在另一個類/方法/代碼塊內部的類,分四類:
class Outer {
private int outerField = 10;
class Inner { // 非靜態
void access() { System.out.println(outerField); } // 可直接訪問外部所有成員
}
}
// 創建:new Outer().new Inner()
Outer.thisclass Outer {
static class StaticInner { // static 修飾
void access() { /* 僅能訪問外部 static 成員 */ }
}
}
// 創建:new Outer.StaticInner() — 無需外部實例
class Outer {
void method() {
final int localVar = 10; // Java 8+ 可省略 final(effectively final)
class LocalInner {
void print() { System.out.println(localVar); }
}
new LocalInner().print();
}
}
Outer$1LocalInner.classfinal 或 effectively final 的局部變數Runnable r = new Runnable() { // 實現接口
@Override public void run() { System.out.println("匿名類"); }
};
Comparator cmp = new Comparator<>() { // Java 9+ 鑽石操作符
@Override public int compare(String a, String b) { return a.length() - b.length(); }
};
public class Goods {
// 內部類對外不可見,完美隱藏
private class ContentImpl implements Content { ... }
private class DestinationImpl implements Destination { ... }
public Content getContent() { return new ContentImpl(); }
public Destination getDestination(String label) { return new DestinationImpl(label); }
}
外部只見介面 Content、Destination,不知具體實現類,降低耦合。
public class Outer {
// 每個內部類可獨立實現不同介面/繼承不同類
class ImplA implements InterfaceA { ... }
class ImplB extends AbstractB { ... }
class ImplC implements InterfaceC { ... }
// 對外提供多種能力
public InterfaceA getA() { return new ImplA(); }
public AbstractB getB() { return new ImplB(); }
}
一個外部類實例可產出多種型別的內部實例,實現邏輯上的「多重繼承」。
public class MyList implements Iterable {
private Node head;
@Override public Iterator iterator() {
return new Iterator() { // 匿名內部類實現 Iterator
Node current = head;
@Override public boolean hasNext() { return current != null; }
@Override public E next() {
E val = current.val;
current = current.next;
return val;
}
};
}
private static class Node { // 靜態內部類:節點結構
E val; Node next;
}
}
Node 為靜態內部類:不依賴外部實例,純數據結構。Iterator 為匿名內部類:捕獲 head 引用,實現遍歷邏輯。