Java学习第2天 - 面向对象编程基础

学习时间: 4-5小时
学习目标: 深入掌握Java面向对象编程核心概念,理解类与对象的关系


📋 详细学习清单

✅ 第一部分:面向对象概念深度理解 (60分钟)

1. 面向对象 vs 面向过程详细对比

JavaScript (你熟悉的函数式编程)

javascript 复制代码
// 面向过程的方式 - 数据和函数分离
let studentName = "张三";
let studentAge = 20;
let studentGrade = 85;
let studentId = "S001";

function showStudentInfo(name, age, grade, id) {
    console.log(`学号:${id}, 姓名:${name}, 年龄:${age}, 成绩:${grade}`);
}

function calculateGPA(grade) {
    return grade / 20; // 简单换算
}

function isPassGrade(grade) {
    return grade >= 60;
}

// 使用时需要传递很多参数
showStudentInfo(studentName, studentAge, studentGrade, studentId);
console.log("GPA:", calculateGPA(studentGrade));
console.log("是否及格:", isPassGrade(studentGrade));

Java (今天学习的面向对象)

java 复制代码
// 面向对象的方式 - 数据和方法封装在一起
public class Student {
    // 属性(成员变量)- 描述对象的特征
    private String studentId;    // 学号
    private String name;         // 姓名
    private int age;            // 年龄
    private double grade;       // 成绩
    
    // 构造函数 - 创建对象时的初始化方法
    public Student(String studentId, String name, int age, double grade) {
        this.studentId = studentId;
        this.name = name;
        this.age = age;
        this.grade = grade;
    }
    
    // 方法(成员函数)- 描述对象的行为
    public void showStudentInfo() {
        System.out.println("学号:" + studentId + 
                         ", 姓名:" + name + 
                         ", 年龄:" + age + 
                         ", 成绩:" + grade);
    }
    
    public double calculateGPA() {
        return grade / 20.0;
    }
    
    public boolean isPassGrade() {
        return grade >= 60;
    }
    
    // 使用时非常简洁
    public static void main(String[] args) {
        Student student = new Student("S001", "张三", 20, 85);
        student.showStudentInfo();
        System.out.println("GPA: " + student.calculateGPA());
        System.out.println("是否及格: " + student.isPassGrade());
    }
}

2. 面向对象三大特性预览

java 复制代码
// 1. 封装(Encapsulation)- 今天重点学习
class BankAccount {
    private double balance;  // 私有属性,外部不能直接访问
    
    public void deposit(double amount) {  // 公有方法,控制访问
        if (amount > 0) {
            balance += amount;
        }
    }
}

// 2. 继承(Inheritance)- 第3天学习
class SavingsAccount extends BankAccount {
    // 继承父类的属性和方法
}

// 3. 多态(Polymorphism)- 第4天学习
BankAccount account = new SavingsAccount();  // 父类引用指向子类对象

✅ 第二部分:类与对象详细讲解 (90分钟)

1. 类的定义详解

类的基本语法结构

java 复制代码
// 类声明的完整语法
[访问修饰符] [修饰符] class 类名 [extends 父类] [implements 接口] {
    // 属性(成员变量)
    [访问修饰符] [修饰符] 数据类型 属性名 [= 初始值];
    
    // 构造函数
    [访问修饰符] 类名(参数列表) {
        // 初始化代码
    }
    
    // 方法(成员函数)
    [访问修饰符] [修饰符] 返回类型 方法名(参数列表) {
        // 方法体
        return 返回值;  // 如果返回类型不是void
    }
}

实际案例:手机类

java 复制代码
// Phone.java
public class Phone {
    // === 属性定义 ===
    // 基本属性
    private String brand;        // 品牌
    private String model;        // 型号
    private String color;        // 颜色
    private double price;        // 价格
    
    // 技术参数
    private int batteryCapacity; // 电池容量(mAh)
    private int storageSpace;    // 存储空间(GB)
    private double screenSize;   // 屏幕尺寸(英寸)
    
    // 状态属性
    private boolean isPowerOn;   // 是否开机
    private int currentBattery;  // 当前电量百分比
    
    // === 构造函数 ===
    // 无参构造函数
    public Phone() {
        this.isPowerOn = false;
        this.currentBattery = 100;
        System.out.println("创建了一个默认手机对象");
    }
    
    // 有参构造函数 - 基本信息
    public Phone(String brand, String model, String color, double price) {
        this.brand = brand;
        this.model = model;
        this.color = color;
        this.price = price;
        this.isPowerOn = false;
        this.currentBattery = 100;
        System.out.println("创建了一个" + brand + " " + model + "手机");
    }
    
    // 有参构造函数 - 完整信息
    public Phone(String brand, String model, String color, double price,
                 int batteryCapacity, int storageSpace, double screenSize) {
        this(brand, model, color, price);  // 调用上面的构造函数
        this.batteryCapacity = batteryCapacity;
        this.storageSpace = storageSpace;
        this.screenSize = screenSize;
        System.out.println("创建了完整配置的手机");
    }
    
    // === 方法定义 ===
    // 开机方法
    public void powerOn() {
        if (!isPowerOn) {
            isPowerOn = true;
            System.out.println(brand + " " + model + " 开机成功!");
            System.out.println("当前电量:" + currentBattery + "%");
        } else {
            System.out.println("手机已经开机了!");
        }
    }
    
    // 关机方法
    public void powerOff() {
        if (isPowerOn) {
            isPowerOn = false;
            System.out.println(brand + " " + model + " 已关机");
        } else {
            System.out.println("手机已经关机了!");
        }
    }
    
    // 打电话方法
    public void makeCall(String phoneNumber) {
        if (!isPowerOn) {
            System.out.println("请先开机!");
            return;
        }
        if (currentBattery <= 0) {
            System.out.println("电量不足,无法打电话!");
            return;
        }
        System.out.println("正在拨打:" + phoneNumber);
        currentBattery -= 2;  // 打电话消耗电量
        System.out.println("通话结束,剩余电量:" + currentBattery + "%");
    }
    
    // 发短信方法
    public void sendMessage(String phoneNumber, String message) {
        if (!isPowerOn) {
            System.out.println("请先开机!");
            return;
        }
        if (currentBattery <= 0) {
            System.out.println("电量不足,无法发送短信!");
            return;
        }
        System.out.println("发送短信到:" + phoneNumber);
        System.out.println("短信内容:" + message);
        currentBattery -= 1;  // 发短信消耗电量
        System.out.println("短信发送成功,剩余电量:" + currentBattery + "%");
    }
    
    // 充电方法
    public void charge(int minutes) {
        System.out.println("开始充电...");
        int chargeAmount = minutes * 2;  // 每分钟充2%
        currentBattery += chargeAmount;
        if (currentBattery > 100) {
            currentBattery = 100;
        }
        System.out.println("充电" + minutes + "分钟,当前电量:" + currentBattery + "%");
    }
    
    // 显示手机信息
    public void showPhoneInfo() {
        System.out.println("=== 手机详细信息 ===");
        System.out.println("品牌:" + brand);
        System.out.println("型号:" + model);
        System.out.println("颜色:" + color);
        System.out.println("价格:¥" + price);
        System.out.println("电池容量:" + batteryCapacity + "mAh");
        System.out.println("存储空间:" + storageSpace + "GB");
        System.out.println("屏幕尺寸:" + screenSize + "英寸");
        System.out.println("开机状态:" + (isPowerOn ? "已开机" : "已关机"));
        System.out.println("当前电量:" + currentBattery + "%");
        System.out.println("==================");
    }
}

2. 对象的创建和使用

java 复制代码
// PhoneTest.java - 测试手机类
public class PhoneTest {
    public static void main(String[] args) {
        System.out.println("=== Java面向对象 - 手机对象测试 ===\n");
        
        // 1. 创建不同的手机对象
        System.out.println("--- 创建手机对象 ---");
        Phone phone1 = new Phone();  // 使用无参构造函数
        
        Phone phone2 = new Phone("苹果", "iPhone 15", "蓝色", 5999.0);
        
        Phone phone3 = new Phone("华为", "Mate 60 Pro", "黑色", 6999.0,
                                5000, 512, 6.82);
        
        // 2. 测试手机功能
        System.out.println("\n--- 测试iPhone 15 ---");
        phone2.showPhoneInfo();
        phone2.powerOn();
        phone2.makeCall("13800138000");
        phone2.sendMessage("13900139000", "你好,这是一条测试短信!");
        phone2.charge(10);
        phone2.powerOff();
        
        System.out.println("\n--- 测试华为 Mate 60 Pro ---");
        phone3.showPhoneInfo();
        phone3.powerOn();
        
        // 模拟连续使用
        for (int i = 1; i <= 20; i++) {
            phone3.makeCall("1390013900" + String.format("%02d", i));
        }
        
        phone3.charge(30);  // 充电30分钟
        phone3.sendMessage("13700137000", "电量充足,可以正常使用了!");
    }
}

✅ 第三部分:封装性详解 (60分钟)

1. 访问修饰符详细说明

java 复制代码
public class AccessModifierExample {
    // public - 公有的,任何地方都可以访问
    public String publicField = "所有人都能看到我";
    
    // private - 私有的,只有当前类内部可以访问
    private String privateField = "只有我自己能看到";
    
    // protected - 受保护的,同包或子类可以访问(后面学习)
    protected String protectedField = "同包和子类能看到我";
    
    // 默认(包私有)- 同包内可以访问
    String packageField = "同包的类能看到我";
    
    // 私有方法 - 内部使用
    private void privateMethod() {
        System.out.println("这是私有方法,外部无法调用");
    }
    
    // 公有方法 - 对外接口
    public void publicMethod() {
        System.out.println("这是公有方法,可以调用私有方法:");
        privateMethod();  // 内部可以调用私有方法
    }
}

2. 属性封装的标准模式:getter和setter

java 复制代码
// Student.java - 标准的封装示例
public class Student {
    // 私有属性
    private String studentId;
    private String name;
    private int age;
    private double score;
    private String major;
    
    // 构造函数
    public Student(String studentId, String name, int age, String major) {
        this.studentId = studentId;
        this.name = name;
        this.setAge(age);  // 使用setter方法,包含验证逻辑
        this.major = major;
        this.score = 0.0;  // 默认分数
    }
    
    // === Getter方法 - 获取属性值 ===
    public String getStudentId() {
        return studentId;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public double getScore() {
        return score;
    }
    
    public String getMajor() {
        return major;
    }
    
    // === Setter方法 - 设置属性值(包含验证逻辑)===
    public void setStudentId(String studentId) {
        if (studentId != null && studentId.length() > 0) {
            this.studentId = studentId;
        } else {
            System.out.println("学号不能为空!");
        }
    }
    
    public void setName(String name) {
        if (name != null && name.trim().length() > 0) {
            this.name = name.trim();
        } else {
            System.out.println("姓名不能为空!");
        }
    }
    
    public void setAge(int age) {
        if (age >= 16 && age <= 65) {
            this.age = age;
        } else {
            System.out.println("年龄必须在16-65岁之间!当前输入:" + age);
        }
    }
    
    public void setScore(double score) {
        if (score >= 0 && score <= 100) {
            this.score = score;
        } else {
            System.out.println("分数必须在0-100之间!当前输入:" + score);
        }
    }
    
    public void setMajor(String major) {
        if (major != null && major.trim().length() > 0) {
            this.major = major.trim();
        } else {
            System.out.println("专业不能为空!");
        }
    }
    
    // === 业务方法 ===
    public String getGradeLevel() {
        if (score >= 90) return "优秀";
        else if (score >= 80) return "良好";
        else if (score >= 70) return "中等";
        else if (score >= 60) return "及格";
        else return "不及格";
    }
    
    public boolean isPass() {
        return score >= 60;
    }
    
    public void study(String subject, int hours) {
        System.out.println(name + " 学习了 " + subject + " " + hours + " 小时");
        // 学习可以提高分数(简单模拟)
        double improvement = hours * 0.5;
        setScore(Math.min(score + improvement, 100));
        System.out.println("学习后分数提升到:" + score);
    }
    
    public void showStudentInfo() {
        System.out.println("=== 学生信息 ===");
        System.out.println("学号:" + studentId);
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
        System.out.println("专业:" + major);
        System.out.println("分数:" + score);
        System.out.println("等级:" + getGradeLevel());
        System.out.println("是否及格:" + (isPass() ? "是" : "否"));
        System.out.println("===============");
    }
}

✅ 第四部分:实战练习 (90分钟)

练习1:银行账户管理系统

java 复制代码
// BankAccount.java
public class BankAccount {
    // 私有属性
    private String accountNumber;    // 账号
    private String accountHolder;    // 账户持有人
    private double balance;         // 余额
    private String accountType;     // 账户类型
    private boolean isActive;       // 账户状态
    
    // 构造函数
    public BankAccount(String accountNumber, String accountHolder, 
                      String accountType, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.accountType = accountType;
        this.setBalance(initialBalance);
        this.isActive = true;
        System.out.println("账户创建成功:" + accountNumber);
    }
    
    // 存款方法
    public void deposit(double amount) {
        if (!isActive) {
            System.out.println("账户已冻结,无法存款!");
            return;
        }
        if (amount <= 0) {
            System.out.println("存款金额必须大于0!");
            return;
        }
        balance += amount;
        System.out.println("存款成功!存入金额:¥" + amount + ",当前余额:¥" + balance);
    }
    
    // 取款方法
    public void withdraw(double amount) {
        if (!isActive) {
            System.out.println("账户已冻结,无法取款!");
            return;
        }
        if (amount <= 0) {
            System.out.println("取款金额必须大于0!");
            return;
        }
        if (amount > balance) {
            System.out.println("余额不足!当前余额:¥" + balance + ",尝试取款:¥" + amount);
            return;
        }
        balance -= amount;
        System.out.println("取款成功!取出金额:¥" + amount + ",当前余额:¥" + balance);
    }
    
    // 转账方法
    public void transfer(BankAccount targetAccount, double amount) {
        if (!isActive) {
            System.out.println("账户已冻结,无法转账!");
            return;
        }
        if (amount <= 0) {
            System.out.println("转账金额必须大于0!");
            return;
        }
        if (amount > balance) {
            System.out.println("余额不足,转账失败!");
            return;
        }
        if (!targetAccount.isActive) {
            System.out.println("目标账户已冻结,转账失败!");
            return;
        }
        
        // 执行转账
        this.balance -= amount;
        targetAccount.balance += amount;
        System.out.println("转账成功!");
        System.out.println("从账户 " + this.accountNumber + " 转出 ¥" + amount);
        System.out.println("到账户 " + targetAccount.accountNumber);
        System.out.println("当前余额:¥" + this.balance);
    }
    
    // 查询余额
    public void checkBalance() {
        System.out.println("账户:" + accountNumber + ",余额:¥" + balance);
    }
    
    // 冻结账户
    public void freezeAccount() {
        isActive = false;
        System.out.println("账户 " + accountNumber + " 已冻结");
    }
    
    // 激活账户
    public void activateAccount() {
        isActive = true;
        System.out.println("账户 " + accountNumber + " 已激活");
    }
    
    // Getter和Setter方法
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public String getAccountHolder() {
        return accountHolder;
    }
    
    public double getBalance() {
        return balance;
    }
    
    private void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        } else {
            this.balance = 0;
            System.out.println("初始余额不能为负数,已设置为0");
        }
    }
    
    public String getAccountType() {
        return accountType;
    }
    
    public boolean isActive() {
        return isActive;
    }
    
    // 显示账户详细信息
    public void showAccountInfo() {
        System.out.println("=== 账户详细信息 ===");
        System.out.println("账号:" + accountNumber);
        System.out.println("持有人:" + accountHolder);
        System.out.println("账户类型:" + accountType);
        System.out.println("余额:¥" + balance);
        System.out.println("状态:" + (isActive ? "正常" : "冻结"));
        System.out.println("==================");
    }
}

测试银行账户系统:

java 复制代码
// BankTest.java
public class BankTest {
    public static void main(String[] args) {
        System.out.println("=== 银行账户管理系统测试 ===\n");
        
        // 创建账户
        BankAccount account1 = new BankAccount("6217001234567890", "张三", "储蓄卡", 1000.0);
        BankAccount account2 = new BankAccount("6217009876543210", "李四", "储蓄卡", 500.0);
        
        // 显示初始状态
        System.out.println("\n--- 初始账户状态 ---");
        account1.showAccountInfo();
        account2.showAccountInfo();
        
        // 测试存款
        System.out.println("\n--- 测试存款功能 ---");
        account1.deposit(500.0);
        account1.deposit(-100.0);  // 测试错误情况
        
        // 测试取款
        System.out.println("\n--- 测试取款功能 ---");
        account1.withdraw(200.0);
        account1.withdraw(2000.0);  // 测试余额不足
        
        // 测试转账
        System.out.println("\n--- 测试转账功能 ---");
        account1.transfer(account2, 300.0);
        
        // 查看转账后状态
        System.out.println("\n--- 转账后账户状态 ---");
        account1.checkBalance();
        account2.checkBalance();
        
        // 测试账户冻结
        System.out.println("\n--- 测试账户冻结 ---");
        account1.freezeAccount();
        account1.deposit(100.0);  // 冻结后尝试存款
        account1.activateAccount();
        account1.deposit(100.0);  // 激活后存款
    }
}

练习2:图书管理类

java 复制代码
// Book.java
public class Book {
    // 私有属性
    private String isbn;          // 书籍编号
    private String title;         // 书名
    private String author;        // 作者
    private String publisher;     // 出版社
    private double price;         // 价格
    private int publishYear;      // 出版年份
    private String category;      // 分类
    private boolean isAvailable; // 是否可借
    private String borrower;      // 借阅者
    
    // 构造函数
    public Book(String isbn, String title, String author, String publisher, 
                double price, int publishYear, String category) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
        this.setPrice(price);
        this.setPublishYear(publishYear);
        this.category = category;
        this.isAvailable = true;
        this.borrower = null;
        System.out.println("图书录入成功:《" + title + "》");
    }
    
    // 借书方法
    public boolean borrowBook(String borrowerName) {
        if (!isAvailable) {
            System.out.println("《" + title + "》已被借出,借阅者:" + borrower);
            return false;
        }
        isAvailable = false;
        borrower = borrowerName;
        System.out.println("借书成功!《" + title + "》已借给:" + borrowerName);
        return true;
    }
    
    // 还书方法
    public boolean returnBook() {
        if (isAvailable) {
            System.out.println("《" + title + "》未被借出,无需还书");
            return false;
        }
        System.out.println("还书成功!《" + title + "》由 " + borrower + " 归还");
        isAvailable = true;
        borrower = null;
        return true;
    }
    
    // 获取图书状态
    public String getBookStatus() {
        if (isAvailable) {
            return "可借";
        } else {
            return "已借出(借阅者:" + borrower + ")";
        }
    }
    
    // Getter和Setter方法
    public String getIsbn() {
        return isbn;
    }
    
    public String getTitle() {
        return title;
    }
    
    public void setTitle(String title) {
        if (title != null && title.trim().length() > 0) {
            this.title = title.trim();
        }
    }
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        if (author != null && author.trim().length() > 0) {
            this.author = author.trim();
        }
    }
    
    public double getPrice() {
        return price;
    }
    
    public void setPrice(double price) {
        if (price >= 0) {
            this.price = price;
        } else {
            System.out.println("价格不能为负数!");
        }
    }
    
    public int getPublishYear() {
        return publishYear;
    }
    
    public void setPublishYear(int year) {
        int currentYear = 2024;  // 假设当前年份
        if (year >= 1000 && year <= currentYear) {
            this.publishYear = year;
        } else {
            System.out.println("出版年份无效!");
        }
    }
    
    public boolean isAvailable() {
        return isAvailable;
    }
    
    public String getBorrower() {
        return borrower;
    }
    
    // 显示图书详细信息
    public void showBookInfo() {
        System.out.println("=== 图书详细信息 ===");
        System.out.println("ISBN:" + isbn);
        System.out.println("书名:《" + title + "》");
        System.out.println("作者:" + author);
        System.out.println("出版社:" + publisher);
        System.out.println("价格:¥" + price);
        System.out.println("出版年份:" + publishYear + "年");
        System.out.println("分类:" + category);
        System.out.println("状态:" + getBookStatus());
        System.out.println("==================");
    }
}

✅ 第五部分:今日作业 (课后完成)

作业1:汽车类设计

创建一个Car类,包含以下要求:

属性要求:

  • 品牌(brand)、型号(model)、颜色(color)
  • 价格(price)、燃料类型(fuelType)
  • 当前速度(currentSpeed)、最大速度(maxSpeed)
  • 油量(fuelLevel)、油箱容量(fuelCapacity)

方法要求:

  • 启动(start)、熄火(stop)
  • 加速(accelerate)、减速(decelerate)
  • 加油(refuel)、显示车辆信息(showCarInfo)

作业2:员工类设计

创建一个Employee类,包含:

属性要求:

  • 员工ID、姓名、部门、职位
  • 基本工资、奖金、工作年限

方法要求:

  • 计算总工资、升职、加薪
  • 显示员工信息、工作统计

作业3:综合练习

创建一个简单的学生成绩管理系统,包含:

  • Student类:学生基本信息
  • Subject类:科目信息
  • Grade类:成绩记录
  • 测试类:创建多个学生,录入成绩,统计分析

📚 今日学习总结

🎯 掌握的核心概念

  1. 面向对象基本概念:类与对象的关系
  2. 封装性:private/public访问控制
  3. 构造函数:对象初始化机制
  4. getter/setter:属性访问的标准模式

🔧 实践技能

  1. 能够设计和实现基本的Java类
  2. 理解属性封装和方法封装
  3. 掌握对象的创建和使用
  4. 能够编写包含验证逻辑的setter方法

📖 明天预习

  • 继承(extends)的概念和语法
  • 方法重写(Override)
  • super关键字的使用
  • 多态的初步概念

恭喜你完成了Java面向对象编程的第一天学习! 🎉

相关推荐
rzl029 分钟前
java web5(黑马)
java·开发语言·前端
guojl29 分钟前
深度解读jdk8 HashMap设计与源码
java
guojl34 分钟前
深度解读jdk8 ConcurrentHashMap设计与源码
java
爱上语文1 小时前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
A~taoker1 小时前
taoker的项目维护(ng服务器)
java·开发语言
HGW6891 小时前
基于 Elasticsearch 实现地图点聚合
java·elasticsearch·高德地图
hi星尘2 小时前
深度解析:Java内部类与外部类的交互机制
java·开发语言·交互
wuxinyan1232 小时前
Java面试题033:一文深入了解MySQL(5)
java·数据库·mysql·面试
清心歌2 小时前
Java SE线程的创建
java
高兴达2 小时前
Spring boot入门工程
java·spring boot·后端