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

Java 類與物件實戰:Student 類別設計、建構子初始化與多物件測試

     編輯:Java 綜合教學

需求分析

設計學生類別 Student,包含:

  • 屬性:學號 (int)、姓名 (String)、年齡 (int)
  • 建構子:Student(int stuNo, String name, int age) 初始化三個屬性
  • 方法:outPut() 輸出學生資訊
  • 主類建立 6 個學生物件測試

Student 類別實作

public class Student {
    private int stuNo;      // 封裝:私有欄位
    private String stuName;
    private int stuAge;
    
    // 建構子初始化
    public Student(int stuNo, String name, int age) {
        this.stuNo = stuNo;
        this.stuName = name;
        this.stuAge = age;
    }
    
    // 輸出資訊
    public void outPut() {
        System.out.printf("%s\t%d\t%d%n", stuName, stuNo, stuAge);
    }
    
    // Getter (良好習慣)
    public int getStuNo() { return stuNo; }
    public String getStuName() { return stuName; }
    public int getStuAge() { return stuAge; }
}

測試主類

public class TestStudent {
    public static void main(String[] args) {
        // 建立 6 個學生物件
        Student[] students = {
            new Student(10001, "張三", 25),
            new Student(10002, "李四", 27),
            new Student(10003, "王五", 22),
            new Student(10004, "馬六", 19),
            new Student(10005, "馮七", 22),
            new Student(10006, "秦八", 26)
        };
        
        // 表頭
        System.out.println("姓名\t學號\t年齡");
        
        // 批次輸出
        for (Student s : students) {
            s.outPut();
        }
    }
}

執行結果

姓名	學號	年齡
張三	10001	25
李四	10002	27
王五	10003	22
馬六	10004	19
馮七	10005	22
秦八	10006	26

程式執行結果截圖

關鍵知識點對比:Clock vs Student

特性Clock 類Student 類
驗證邏輯有 (時間範圍檢查)無 (簡單資料載體)
建構子參數三個 intint, String, int
輸出格式printf 格式化簡單制表符分隔
錯誤處理列印錯誤訊息不處理 (假設輸入合法)
封裝程度私有欄位 + 私有驗證方法私有欄位 + 公共 Getter

進階擴充:資料驗證版 Student

public class Student {
    private int stuNo;
    private String stuName;
    private int stuAge;
    
    public Student(int stuNo, String name, int age) {
        if (stuNo <= 0) throw new IllegalArgumentException("學號必須為正整數");
        if (name == null || name.trim().isEmpty()) throw new IllegalArgumentException("姓名不可為空");
        if (age < 0 || age > 150) throw new IllegalArgumentException("年齡範圍 0-150");
        
        this.stuNo = stuNo;
        this.stuName = name;
        this.stuAge = age;
    }
    // ... 其他方法
}

物件陣列 vs 集合

// 物件陣列 (固定大小)
Student[] arr = new Student[6];

// ArrayList (動態擴充、豐富 API)
List list = new ArrayList<>();
list.add(new Student(10001, "張三", 25));
// ... 
list.forEach(Student::outPut); // Java 8+ Lambda 遍歷

常見新手錯誤避坑

  • ❌ 類別名未加 public 導致其他套件無法使用
  • ❌ 建構子寫了回傳型別 void Student() → 變成普通方法
  • ❌ 忘記 this. 區分參數與欄位:stuNo = stuNo (自我賦值)
  • ❌ 主類檔名與 public class 名稱不一致
  • ✅ 習慣:欄位私有、建構子初始化、提供 Getter、主類獨立檔案
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved