對象是面向對象程序的核心。本文詳細拆解對象的聲明、實例化、初始化三階段,以及對象對屬性和方法的訪問規則,並通過代碼示例演示 this 關鍵字的作用。
Student zhangsan = new Student(); // 一條語句包含三個動作
| 階段 | 動作 | 說明 |
|---|---|---|
| 1. 聲明 | Student zhangsan | 在棧內存分配引用變量空間(32/64 位地址),不分配對象內存,值為 null |
| 2. 實例化 | new Student() | 在堆內存分配對象內存,調用構造器,返回對象地址賦給引用 |
| 3. 初始化 | 構造器執行 | 為實例變量賦初始值(顯式/默認),執行構造器代碼體 |
記住: 聲明≠創建對象;new 才是真正創建對象的關鍵字,每次 new 都在堆中開闢新空間。
class Student {
float height, weight;
String head, ear, hand, foot, mouth;
// 顯式無參構造器
Student() {
height = 0; weight = 0;
head = "myhead"; ear = "myear";
hand = "myhand"; foot = "myfoot"; mouth = "mymouth";
System.out.println("new Student ok!!!");
}
}
public class Man {
public static void main(String[] args) {
Student zhangsan = new Student(); // 調用無參構造器
}
}
// 輸出:new Student ok!!!
通過 引用.屬性 或 引用.方法(參數) 訪問。訪問權限由修飾符(private/public/protected/默認)控制。
zhangsan.height = 175.5f;
System.out.println(zhangsan.name);
class Person {
float height, weight;
String name;
Person() {
height = 175; weight = 70; name = "zhangsan";
System.out.println("new Person ok!!!");
}
void speak(String words) {
System.out.println("say: " + words);
}
}
public class Human {
public static void main(String[] args) {
Person zhangsan = new Person();
zhangsan.speak("hello java!!!"); // 調用方法
Person lisi = new Person();
lisi.name = "lisi"; // 修改屬性
lisi.speak("I am studying java!!!");
}
}
/* 輸出:
new Person ok!!!
say: hello java!!!
new Person ok!!!
say: I am studying java!!!
*/
當方法參數/局部變量與實例變量同名時,this.變量名 明確指代實例變量,解決遮蔽衝突。
class Person {
String name;
int age;
// 構造器參數同名
Person(String name, int age) {
this.name = name; // this.name = 實例變量,name = 參數
this.age = age;
}
void printInfo() {
System.out.println(this.name + " - " + this.age); // 此處 this 可省略
}
}
this 還可用於:
this(...) 必須在首行return this; 支持鏈式調用other.method(this)
棧 (Stack) 堆
┌──────────────┐ ┌──────────────────────┐
│ zhangsan ────────────────► │ Student Object │
│ (引用/地址) │ │ height: 0.0 │
└──────────────┘ │ weight: 0.0 │
│ head: "myhead" │
│ ... │
└──────────────────────┘
引用像「遙控器」,對象像「電視機」;一個對象可被多個引用指向(共享),引用賦值為 null 或超出作用域後,對象可能被 GC 回收。
掌握「聲明在棧、實例在堆、構造器初始化、this 解決同名」這條主線,是理解 Java 面向對象運行機制的基石。建議在 IDEA Debug 模式下觀察變量面板,直觀感受引用與對象的關係。