Java面向对象基础:类和对象初探

1.类和对象:蓝图和实物

什么是类?

是对象的蓝图或模板。就像汽车设计图,定义了汽车应该有什么特征和功能。

什么是对象?

对象是根据类创建的具体实例。就像根据设计图制造出来的具体汽车。

Java 复制代码
public class ClassAndObjectDemo {
    public static void main(String[] args) {
        System.out.println("=== 类和对象初体验 ===");
        
        // 创建Student类的对象
        Student student1 = new Student();
        
        // 设置对象的属性
        student1.name = "张三";
        student1.age = 18;
        student1.grade = 85;
        
        // 调用对象的方法
        student1.introduce();
        student1.study();
        
        System.out.println("------------------");
        
        // 创建第二个对象
        Student student2 = new Student();
        student2.name = "李四";
        student2.age = 19;
        student2.grade = 92;
        
        student2.introduce();
        student2.study();
    }
}

// 定义一个Student类
class Student {
    // 属性(也叫字段)
    String name;    // 姓名
    int age;        // 年龄
    int grade;      // 成绩
    
    // 方法(行为)
    void introduce() {
        System.out.println("大家好,我叫" + name + ",今年" + age + "岁");
    }
    
    void study() {
        System.out.println(name + "正在努力学习,成绩是:" + grade + "分");
    }
}

运行结果:

Java 复制代码
=== 类和对象初体验 ===
大家好,我叫张三,今年18岁
张三正在努力学习,成绩是:85分
------------------
大家好,我叫李四,今年19岁
李四正在努力学习,成绩是:92分

2. 方法:对象的行为

2.1 什么是方法?

方法是对象能够执行的操作。就像人的"吃饭"、"睡觉"、"学习"等行为。

Java 复制代码
public class MethodDemo {
    public static void main(String[] args) {
        System.out.println("=== 方法示例 ===");
        
        // 创建Calculator对象
        Calculator calc = new Calculator();
        
        // 调用方法
        int sum = calc.add(5, 3);
        int difference = calc.subtract(10, 4);
        int product = calc.multiply(6, 7);
        double quotient = calc.divide(15, 4);
        
        System.out.println("5 + 3 = " + sum);
        System.out.println("10 - 4 = " + difference);
        System.out.println("6 × 7 = " + product);
        System.out.println("15 ÷ 4 = " + quotient);
        
        // 调用无返回值的方法
        calc.printWelcome();
    }
}

class Calculator {
    // 加法方法
    int add(int a, int b) {
        return a + b;
    }
    
    // 减法方法
    int subtract(int a, int b) {
        return a - b;
    }
    
    // 乘法方法
    int multiply(int a, int b) {
        return a * b;
    }
    
    // 除法方法
    double divide(int a, int b) {
        return (double) a / b;  // 强制类型转换,得到小数结果
    }
    
    // 无返回值的方法
    void printWelcome() {
        System.out.println("欢迎使用计算器!");
    }
}

2.2 方法重载:同名不同参

Java 复制代码
public class MethodOverloading {
    public static void main(String[] args) {
        System.out.println("=== 方法重载 ===");
        
        MathOperations math = new MathOperations();
        
        // 调用不同的add方法
        System.out.println("两个整数相加: " + math.add(5, 3));
        System.out.println("三个整数相加: " + math.add(1, 2, 3));
        System.out.println("两个小数相加: " + math.add(2.5, 3.7));
        System.out.println("整数和小数相加: " + math.add(5, 2.5));
    }
}

class MathOperations {
    // 方法1:两个整数相加
    int add(int a, int b) {
        return a + b;
    }
    
    // 方法2:三个整数相加(重载)
    int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // 方法3:两个小数相加(重载)
    double add(double a, double b) {
        return a + b;
    }
    
    // 方法4:整数和小数相加(重载)
    double add(int a, double b) {
        return a + b;
    }
}

3.构造方法:对象的"出生证明"

3.1 什么是构造方法?

构造方法是在创建对象时自动调用的特殊方法,用于初始化对象。

Java 复制代码
public class ConstructorDemo {
    public static void main(String[] args) {
        System.out.println("=== 构造方法 ===");
        
        // 使用构造方法创建对象
        Person person1 = new Person("张三", 20);
        Person person2 = new Person("李四", 22);
        Person person3 = new Person();  // 使用无参构造方法
        
        person1.introduce();
        person2.introduce();
        person3.introduce();
    }
}

class Person {
    String name;
    int age;
    
    // 无参构造方法(默认构造方法)
    Person() {
        this.name = "未知";
        this.age = 0;
        System.out.println("创建了一个Person对象(使用无参构造)");
    }
    
    // 有参构造方法
    Person(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("创建了一个Person对象(使用有参构造)");
    }
    
    void introduce() {
        System.out.println("姓名:" + name + ",年龄:" + age);
    }
}

4.this关键字:指代当前对象

Java 复制代码
public class ThisKeyword {
    public static void main(String[] args) {
        System.out.println("=== this关键字 ===");
        
        Book book1 = new Book("Java编程", "张三", 59.9);
        Book book2 = new Book("Python入门", "李四", 49.9);
        
        book1.displayInfo();
        book2.displayInfo();
    }
}

class Book {
    String title;
    String author;
    double price;
    
    // 构造方法中使用this
    Book(String title, String author, double price) {
        this.title = title;    // this.title指类的属性,title指参数
        this.author = author;
        this.price = price;
    }
    
    void displayInfo() {
        System.out.println("书名:" + this.title);
        System.out.println("作者:" + this.author);
        System.out.println("价格:" + this.price + "元");
        System.out.println("这本书的作者是" + getAuthor());  // 调用本类的方法
    }
    
    String getAuthor() {
        return this.author;  // 使用this指代当前对象
    }
}

5.综合示例:简单的银行账户系统

Java 复制代码
public class BankAccountSystem {
    public static void main(String[] args) {
        System.out.println("=== 银行账户系统 ===");
        
        // 创建账户
        BankAccount account1 = new BankAccount("张三", "1001");
        BankAccount account2 = new BankAccount("李四", "1002", 5000);
        
        // 显示账户信息
        account1.displayInfo();
        account2.displayInfo();
        
        System.out.println("------------------");
        
        // 存款
        account1.deposit(1000);
        account2.deposit(2000);
        
        System.out.println("------------------");
        
        // 取款
        account1.withdraw(500);
        account2.withdraw(8000);  // 尝试取款超过余额
        
        System.out.println("------------------");
        
        // 转账
        account2.transfer(account1, 1000);
        
        System.out.println("------------------");
        
        // 最终余额
        System.out.println("最终余额:");
        account1.displayInfo();
        account2.displayInfo();
    }
}

class BankAccount {
    String accountHolder;  // 账户持有人
    String accountNumber;  // 账户号码
    double balance;        // 余额
    
    // 构造方法1:只传姓名和账号
    BankAccount(String accountHolder, String accountNumber) {
        this.accountHolder = accountHolder;
        this.accountNumber = accountNumber;
        this.balance = 0;  // 默认余额为0
    }
    
    // 构造方法2:传所有信息
    BankAccount(String accountHolder, String accountNumber, double initialBalance) {
        this.accountHolder = accountHolder;
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }
    
    // 存款
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println(accountHolder + " 存款 " + amount + " 元成功");
            System.out.println("当前余额:" + balance + " 元");
        } else {
            System.out.println("存款金额必须大于0");
        }
    }
    
    // 取款
    void withdraw(double amount) {
        if (amount <= 0) {
            System.out.println("取款金额必须大于0");
        } else if (amount > balance) {
            System.out.println(accountHolder + " 取款失败,余额不足");
            System.out.println("当前余额:" + balance + " 元,取款金额:" + amount + " 元");
        } else {
            balance -= amount;
            System.out.println(accountHolder + " 取款 " + amount + " 元成功");
            System.out.println("当前余额:" + balance + " 元");
        }
    }
    
    // 转账
    void transfer(BankAccount targetAccount, double amount) {
        if (amount <= 0) {
            System.out.println("转账金额必须大于0");
        } else if (amount > balance) {
            System.out.println(accountHolder + " 转账失败,余额不足");
        } else {
            this.withdraw(amount);  // 从当前账户扣款
            targetAccount.deposit(amount);  // 向目标账户存款
            System.out.println(accountHolder + " 向 " + targetAccount.accountHolder + 
                             " 转账 " + amount + " 元成功");
        }
    }
    
    // 显示账户信息
    void displayInfo() {
        System.out.println("账户信息:");
        System.out.println("  持有人:" + accountHolder);
        System.out.println("  账号:" + accountNumber);
        System.out.println("  余额:" + balance + " 元");
    }
}

运行结果:

Java 复制代码
=== 银行账户系统 ===
账户信息:
  持有人:张三
  账号:1001
  余额:0.0 元
账户信息:
  持有人:李四
  账号:1002
  余额:5000.0 元
------------------
张三 存款 1000.0 元成功
当前余额:1000.0 元
李四 存款 2000.0 元成功
当前余额:7000.0 元
------------------
张三 取款 500.0 元成功
当前余额:500.0 元
李四 取款失败,余额不足
当前余额:7000.0 元,取款金额:8000.0 元
------------------
李四 取款 1000.0 元成功
当前余额:6000.0 元
张三 存款 1000.0 元成功
当前余额:1500.0 元
李四 向 张三 转账 1000.0 元成功
------------------
最终余额:
账户信息:
  持有人:张三
  账号:1001
  余额:1500.0 元
账户信息:
  持有人:李四
  账号:1002
  余额:6000.0 元

6.常见错误和注意事项

错误示例:

Java 复制代码
public class CommonMistakes {
    public static void main(String[] args) {
        // 错误1:忘记使用new创建对象
        // Student s;  // 这只是声明,没有创建对象
        // s.name = "张三";  // ❌ 运行时错误:空指针异常
        
        // 正确做法:
        Student s = new Student();  // ✅ 使用new创建对象
        s.name = "张三";
        
        // 错误2:混淆类和对象
        // Student.name = "张三";  // ❌ 错误:应该用对象访问属性
        
        // 错误3:忘记初始化对象属性
        Product p = new Product();
        // 如果没有在构造方法中初始化,属性可能有默认值
        System.out.println(p.name);  // 输出:null
        System.out.println(p.price); // 输出:0.0
    }
}

class Student {
    String name;
}

class Product {
    String name;
    double price;
}

正确做法:

Java 复制代码
public class BestPractices {
    public static void main(String[] args) {
        // 1. 创建对象后立即初始化
        Employee emp = new Employee("张三", "工程师", 8000);
        
        // 2. 使用方法而不是直接操作属性
        emp.displayInfo();
        emp.giveRaise(1000);  // 通过方法修改属性
        
        // 3. 一个类一个文件(实际开发中)
        // 通常每个类放在单独的.java文件中
    }
}

class Employee {
    private String name;
    private String position;
    private double salary;
    
    // 构造方法初始化所有属性
    public Employee(String name, String position, double salary) {
        this.name = name;
        this.position = position;
        this.salary = salary;
    }
    
    // 通过方法访问和修改属性
    public void displayInfo() {
        System.out.println("姓名:" + name);
        System.out.println("职位:" + position);
        System.out.println("薪水:" + salary);
    }
    
    public void giveRaise(double amount) {
        if (amount > 0) {
            salary += amount;
            System.out.println(name + " 加薪 " + amount + " 元");
        }
    }
}

快速记忆口诀

  1. 类是蓝图,对象是实物
    • 类 = 汽车设计图
    • 对象 = 具体的汽车
  2. 属性是特征,方法是行为
    • 属性:姓名、年龄、颜色
    • 方法:吃饭、睡觉、学习
  3. new关键字创对象
    • Student s = new Student();
    • 一定要用new
  4. 构造方法初始化
    • 在创建对象时自动调用
    • 用于设置初始值

八、总结:最重要的三点

  1. 类和对象的关系
    • 类是用来创建对象的模板
    • 对象是类的具体实例
  2. 属性和方法
    • 属性描述对象的状态(是什么)
    • 方法描述对象的行为(能做什么)
  3. 构造方法的作用
    • 在创建对象时初始化属性
    • 确保对象创建后就有合理的状态
相关推荐
寻找华年的锦瑟1 小时前
Qt-QStackedWidget
java·数据库·qt
洲星河ZXH1 小时前
Java,比较器
java·开发语言·算法
l***37091 小时前
spring 跨域CORS Filter
java·后端·spring
CoderYanger1 小时前
递归、搜索与回溯-FloodFill:33.太平洋大西洋水流问题
java·算法·leetcode·1024程序员节
P***84391 小时前
idea创建springBoot的五种方式
java·spring boot·intellij-idea
yuanhello2 小时前
【Android】Android的键值对存储方案对比
android·java·android studio
2501_941142932 小时前
云原生微服务环境下服务熔断与降级优化实践——提升系统稳定性与容错能力
java·大数据·网络
2501_941404312 小时前
多云环境下微服务化AI大模型的企业部署与优化实践指南
java
浩瀚地学2 小时前
【Java】数组
java·开发语言