类的定义

在 Java 中,使用 class 关键字来定义类。类包含成员变量(属性)和成员方法(行为)。

Student.java
public class Student {
    // 成员变量(属性)—— 描述对象的特征
    String name;
    int age;
    int score;

    // 构造方法:创建对象时自动调用,用于初始化对象
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.score = 0;
    }

    // 成员方法(行为)—— 描述对象能做什么
    public void study() {
        System.out.println(name + "正在学习...");
        score += 5;
    }

    public void introduce() {
        System.out.println("我叫" + name + ",今年" + age + "岁,成绩是" + score);
    }
}

创建和使用对象

类是抽象的模板,对象是具体的实例。使用 new 关键字创建对象。

使用 Student 类
public class Main {
    public static void main(String[] args) {
        // 创建对象(使用 new 关键字 + 构造方法)
        Student student1 = new Student("张三", 20);
        Student student2 = new Student("李四", 19);

        // 调用方法
        student1.introduce();   // 我叫张三,今年20岁,成绩是0
        student1.study();      // 张三正在学习...
        student1.introduce();   // 成绩变成5

        student2.introduce();   // 我叫李四,今年19岁,成绩是0
    }
}
💡 this 关键字

this 表示当前对象。当成员变量和方法参数同名时,需要用 this.变量名 来区分。例如 this.name = name 中,左边的 this.name 是成员变量,右边的 name 是参数。

课后练习

以下关于类与对象的说法,正确的是?

A 一个类只能创建一个对象
B 类是对象的模板,对象是类的实例
C 对象的成员变量可以直接用类名访问
D 构造方法必须有返回值