元数据卡
- 前置知识:第7章(上)——初识面向对象
- 预计时间:15 分钟
- 完成标志:能在类中定义字段和方法,会用
this解决命名冲突
行为不能丢
老陈说:"一个类不光有数据(字段),还得有行为(方法)。否则就是一本死书——书能借出、能归还,这些行为应该写在类里面。"
把行为和数据的代码放在一起——这就是面向对象的雏形:
java
class Book {
// 字段(数据)
String title;
String author;
boolean isBorrowed;
// 方法(行为)
void borrow() {
isBorrowed = true;
}
void returnBook() {
isBorrowed = false;
}
void showInfo() {
System.out.println("书名:" + title + ",借出状态:" + isBorrowed);
}
}语言:Java 如何运行:和
main方法一起编译即可
调用方法:
java
public class Library {
public static void main(String[] args) {
Book b = new Book();
b.title = "Java 核心技术";
b.borrow();
System.out.println(b.isBorrowed); // true
b.showInfo(); // 书名:Java 核心技术,借出状态:true
}
}语言:Java 预期输出:
true书名:Java 核心技术,借出状态:true
方法内部可以直接访问同类中的字段——不需要把字段当参数传进去。因为方法"属于"对象,它天然知道自己的字段。
我指的是我自己——this
构造方法(下一节细讲)中经常遇到一个问题——参数名和字段名撞车了:
java
Book(String title, String author) {
title = title; // ❌ 等号两边都是参数,字段根本没被赋值!
}怎么破?用 this:
java
Book(String title, String author) {
this.title = title; // ✅ this.title 是字段,title 是参数
this.author = author;
}语言:Java 说明:
this指向"当前对象"——调用这个方法的那个对象
this 解决了参数名和字段名冲突的问题。多数时候你会看到这种写法——这不是啰嗦,是准确表达意图。
方法里也一样:
java
class Student {
String name;
void setName(String name) {
this.name = name; // 不加 this,name 指的是参数自己
}
void greet() {
System.out.println("你好,我是" + this.name); // this 可省
}
}关键理解:当参数名和字段名不同时,
this可省略。当它们相同时,必须用this。
this 还有一个用途——调用同一个类的其他构造方法:
java
class Book {
String title;
String author;
double price;
Book(String title, String author) {
this(title, author, 0.0); // 调用下面的三参数构造
}
Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
}规则:
this(...)调用必须写在构造方法的第一行。这叫"构造方法链"。
差异窗口:C++ 与 Python
C++ 中 this 是一个指针,访问成员用 ->:
cpp
void setName(const string& name) {
this->name = name; // 指针语法
}Python 中 self 等价于 Java 的 this,但参数必须显式写在方法声明中:
python
class Student:
def set_name(self, name):
self.name = name # self 必须作为第一个参数
def greet(self):
print(f"你好,我是{self.name}")下一步
每次 new Book() 之后都得手动赋值——太麻烦。有个自动执行的"初始化仪式"能一步到位。怎么做到?
下一节:构造方法 → ch07-constructors.md