首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 基礎教程:物件的方法與資料成員深度解析

     編輯:Java 程式設計入門

物件結構回顧

  • 資料成員: 表示物件狀態
  • 方法: 表示物件行為
  • 類別: 物件的藍圖,同類物件共享方法碼、各自擁有資料副本

方法存取資料成員


class Human {
    int height;  // 資料成員
    
    // 存取器
    int getHeight() {
        return this.height;  // this 參考當前物件
    }
}

this 關鍵字

  • this.field:存取實例欄位(區分同名區域變數)
  • this.method():呼叫同一物件的其他方法
  • 隱性參數:每個實例方法自動接收 this
  • 非必要但建議使用,提高可讀性

省略 this


// 這兩種寫法等效
int getHeight() { return this.height; }
int getHeight() { return height; }  // 編譯器自動判斷為實例欄位

方法參數列表


class Human {
    int height;
    
    // 參數列表:(int h)
    void growHeight(int h) {
        this.height = this.height + h;  // 使用參數
    }
}

Human h = new Human();
h.growHeight(10);  // 傳遞實參 10
  • 參數在方法簽名中宣告類型
  • 實參傳遞時進行類型檢查
  • 參數作用域僅限方法內部
  • Java 採用傳值呼叫:基本型別傳值、參考型別傳參考值

方法呼叫其他方法


class Human {
    void breath() {
        System.out.println("hu...hu...");
    }
    
    void repeatBreath(int rep) {
        for (int i = 0; i < rep; i++) {
            this.breath();  // 呼叫同一物件的 breath()
        }
    }
}
  • 區域變數 i 作用域限於 repeatBreath() 內部
  • 類似 C 函數的自動變數

資料成員初始化三種方式

1. 預設初始化

不指定值,Java 自動賦予預設值(0、false、null)。

2. 顯式初始化


class Human {
    int height = 175;  // 宣告時直接賦值
}

硬編碼在類別中,所有實例共享相同初始值。

3. 建構子初始化


class Human {
    int height;
    
    Human(int h) {
        this.height = h;  // 靈活指定每個實例不同初始值
    }
}

優先級最高,可根據建構參數動態決定。

完整範例:銀行帳戶


class BankAccount {
    // 資料成員
    private String accountNumber;
    private String ownerName;
    private double balance;
    private static int totalAccounts = 0;  // 靜態成員
    
    // 顯式初始化
    private boolean active = true;
    
    // 建構子
    public BankAccount(String accountNumber, String ownerName, double initialBalance) {
        this.accountNumber = accountNumber;
        this.ownerName = ownerName;
        this.balance = initialBalance;
        totalAccounts++;
        System.out.println("帳戶建立: " + accountNumber);
    }
    
    // 方法
    public void deposit(double amount) {
        if (amount > 0 && active) {
            balance += amount;
            System.out.println("存入: " + amount + ", 餘額: " + balance);
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && active && balance >= amount) {
            balance -= amount;
            System.out.println("提領: " + amount + ", 餘額: " + balance);
        } else {
            System.out.println("提領失敗: 餘額不足或帳戶停用");
        }
    }
    
    public double getBalance() { return balance; }
    public String getOwnerName() { return ownerName; }
    public static int getTotalAccounts() { return totalAccounts; }
}

public class BankDemo {
    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("A001", "Alice", 1000);
        BankAccount acc2 = new BankAccount("A002", "Bob", 500);
        
        acc1.deposit(200);
        acc1.withdraw(150);
        acc2.withdraw(600);  // 失敗
        
        System.out.println("總帳戶數: " + BankAccount.getTotalAccounts());
    }
}

記憶體模型圖解


Heap (堆疊)
├── BankAccount 物件 1 (acc1)
│   ├── accountNumber: "A001"
│   ├── ownerName: "Alice"
│   ├── balance: 1050.0
│   └── active: true
├── BankAccount 物件 2 (acc2)
│   ├── accountNumber: "A002"
│   ├── ownerName: "Bob"
│   ├── balance: 500.0
│   └── active: true
└── 靜態區域
    └── totalAccounts: 2

Stack (棧) - main() 執行緒
├── acc1 參考 ──────────→ BankAccount 物件 1
├── acc2 參考 ──────────→ BankAccount 物件 2
└── 區域變數...

關鍵概念總結

概念說明關鍵字/語法
資料成員物件狀態儲存欄位宣告
方法物件行為定義方法宣告
this當前物件參考this.field, this.method()
return方法回傳值return expression;
參數方法輸入(Type name, ...)
初始化欄位賦初值預設/顯式/建構子
靜態成員類別層級共享static

常見錯誤

錯誤原因修正
非靜態欄位無法從靜態上下文存取static 方法嘗試用 this.field移除 static、或改用實例參考
區域變數可能未初始化宣告未賦值就使用宣告時初始化、或所有路徑都賦值
參數遮蔽欄位參數名與欄位名相同且未用 this使用 this.field、或改變參數名
傳值呼叫誤解以為修改參數會影響實參基本型別傳值、參考型別傳參考值(可修改物件內容但不可換參考)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved