从0开始学Java--day7--类与对象-初
由于最近有点状况,更新稍有延迟,后续会把这部分内容更详细拆分出来
Java类与对象详解
一、基础概念与认识
类(Class)
类是对象的模板/蓝图,定义了对象的属性(成员变量)和行为(方法)。public class Person { // 类声明// 成员变量(属性)String name; int age;// 成员方法(行为)void introduce() {System.out.println("我叫" + name + ",今年" + age + "岁");} }对象(Object)
对象是类的具体实例,通过new关键字创建。Person p1 = new Person(); // 创建Person类的对象 p1.name = "张三"; // 设置属性 p1.age = 25; p1.introduce(); // 调用方法 → 输出:我叫张三,今年25岁
二、类与对象的交互
对象间调用
对象通过方法参数传递交互:public class BankAccount {double balance;void transfer(BankAccount target, double amount) {this.balance -= amount;target.balance += amount;} }// 使用示例 BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(); acc1.balance = 1000; acc2.balance = 500; acc1.transfer(acc2, 300); // acc1向acc2转账练习1:图书借阅系统
public class Book {String title;boolean isBorrowed;void borrow() {if (!isBorrowed) {isBorrowed = true;System.out.println(title + "借阅成功");} else {System.out.println("该书已被借出");}} }public class Library {void processBorrow(Book book) {book.borrow();} }// 测试 Book javaBook = new Book(); javaBook.title = "Java核心技术"; Library lib = new Library(); lib.processBorrow(javaBook); // 输出:Java核心技术借阅成功
三、对象实例化详解
实例化过程
new Person()执行流程:- JVM分配内存空间
- 初始化成员变量(默认值)
- 调用构造方法
默认初始化值
类型 默认值 int0 double0.0 booleanfalse引用类型 null练习2:学生成绩分析
public class Student {String name;double score; // 默认0.0void printStatus() {if (score == 0.0) {System.out.println(name + "未录入成绩");} else if (score >= 60) {System.out.println(name + "及格");} else {System.out.println(name + "不及格");}} }// 测试 Student s = new Student(); s.name = "李四"; s.printStatus(); // 输出:李四未录入成绩(注意默认值陷阱)
四、this关键字深度解析
三大作用(只能在类中)
- 区分成员变量与局部变量
public class Circle {double radius;void setRadius(double radius) {this.radius = radius; // this.radius指成员变量} } - 在构造方法中调用其他构造方法
public class Employee {String id;String department;public Employee(String id) {this(id, "未分配"); // 调用双参构造}public Employee(String id, String department) {this.id = id;this.department = department;} } - 返回当前对象引用
public class Counter {int count;Counter increment() {count++;return this; // 返回当前对象} }
- 区分成员变量与局部变量
练习3:链式调用
public class StringBuilderDemo {private String value = "";StringBuilderDemo append(String str) {this.value += str;return this; // 支持链式调用}void print() {System.out.println(value);} }// 测试 new StringBuilderDemo().append("Hello").append(" ").append("World").print(); // 输出:Hello World
五、构造方法与初始化
构造方法特点
- 方法名与类名相同
- 无返回类型声明
- 可重载(多个不同参数的构造方法)
- 未定义时系统提供默认无参构造
初始化流程
graph TDA[new 关键字] --> B[分配内存空间]B --> C[成员变量默认初始化]C --> D[显式初始化/初始化块]D --> E[构造方法执行]构造方法陷阱
坑1: 自定义构造方法后默认构造方法消失public class Phone {String model;public Phone(String model) { // 自定义构造方法this.model = model;} }// 编译错误:找不到无参构造 Phone p = new Phone();坑2: 循环调用构造方法
public class ErrorExample {public ErrorExample() {this("default"); // 编译通过}public ErrorExample(String s) {this(); // 报错} }练习4:坐标点构造
public class Point {int x;int y;// 无参构造(初始化为原点)public Point() {this(0, 0); // 调用双参构造}// 单参构造(x=y)public Point(int value) {this(value, value);}// 双参构造public Point(int x, int y) {this.x = x;this.y = y;} }
六、综合练习:银行账户系统
public class BankAccount {private String accountId;private double balance;// 构造方法1:仅账号public BankAccount(String accountId) {this(accountId, 0.0); // 调用双参构造}// 构造方法2:账号+初始余额public BankAccount(String accountId, double initBalance) {this.accountId = accountId;if (initBalance < 0) { // 防止负初始值System.out.println("警告:初始余额不能为负,自动设置为0");this.balance = 0;} else {this.balance = initBalance;}}// 存款public void deposit(double amount) {if (amount > 0) {this.balance += amount;} else {System.out.println("存款金额必须大于0");}}// 取款public boolean withdraw(double amount) {if (amount > balance) {System.out.println("余额不足");return false;}if (amount <= 0) {System.out.println("取款金额必须大于0");return false;}balance -= amount;return true;}// 转账public void transferTo(BankAccount target, double amount) {if (this.withdraw(amount)) { // 先扣款target.deposit(amount); // 再存款System.out.println("转账成功");}}// 显示余额public void display() {System.out.printf("账户 %s 余额:%.2f元%n", accountId, balance);}
}// 测试类
public class BankTest {public static void main(String[] args) {BankAccount acc1 = new BankAccount("001");BankAccount acc2 = new BankAccount("002", 500);acc1.deposit(1000);acc1.transferTo(acc2, 300);acc1.display(); // 账户 001 余额:700.00元acc2.display(); // 账户 002 余额:800.00元// 测试异常情况acc1.withdraw(-50); // 取款金额必须大于0acc1.transferTo(acc2, 1000); // 余额不足}
}
七、关键要点总结
类与对象关系
- 类是模板(设计图),对象是实例(具体产品)
- 一个类可创建多个对象
实例化注意事项
- 未初始化成员变量使用默认值(
null,0,false等) - 对象未被引用时成为垃圾,由GC回收
- 未初始化成员变量使用默认值(
this核心用法
- 解决命名冲突:
this.成员变量 - 构造方法互调:
this(...) - 返回当前对象:方法返回
this
- 解决命名冲突:
构造方法最佳实践
- 始终保留无参构造(或显式定义)
- 参数校验(如金额非负)
- 避免循环调用
- 使用
this(...)减少代码重复
通过本教程的3000+字详细解析和7个实战练习,您已掌握Java面向对象的核心机制。实际开发中,建议结合封装、继承、多态等特性构建更健壮的系统。
