Java 类与对象

类与对象是 Java 的灵魂——Java 是"纯"面向对象语言,所有代码都写在类里。本章带你彻底理解四个词:类、对象、字段、方法。掌握这一章,你才真正"入门"了 Java。

1. 类是图纸,对象是实物

类(Class)是"图纸"——定义一类事物有哪些属性(字段)和行为(方法)。对象(Object)是根据图纸造出来的具体实例。一个类可以造出无数个对象,每个对象有独立的字段值。

// 类是创建对象的"图纸"
class Student {

    // 字段(成员变量)——对象的状态
    String name;
    int age;
    double score;

    // 构造方法:与类同名,无返回类型
    // 用于创建对象时初始化字段
    public Student(String name, int age) {
        // this 指向"当前正在创建的对象"
        // 当参数名和字段名冲突时,必须用 this 区分
        this.name = name;
        this.age = age;
    }

    // 方法(成员方法)——对象的行为
    public String introduce() {
        return "我叫 " + name + ",今年 " + age + " 岁";
    }

    public boolean isPassed() {
        return score >= 60;
    }
}

// 主程序
public class ClassDemo {
    public static void main(String[] args) {
        // new 创建对象:在堆上分配内存,调用构造方法
        Student s1 = new Student("小明", 20);
        Student s2 = new Student("小红", 22);

        s1.score = 85.5;
        s2.score = 55;

        System.out.println(s1.introduce());      // 我叫 小明,今年 20 岁
        System.out.println(s2.introduce());      // 我叫 小红,今年 22 岁

        System.out.println(s1.isPassed());       // true
        System.out.println(s2.isPassed());       // false
    }
}

几个核心要点:

2. 构造方法重载与 this()

构造方法可以重载(同名字段不同参数列表)。一个构造方法可以用 this(...) 调用另一个构造方法,避免重复初始化代码:

class Point {
    double x, y;

    // 构造方法重载:同 this() 调用另一个构造方法
    public Point() {
        this(0, 0);              // 调用下面的双参构造,避免重复代码
    }

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Point p1 = new Point();              // 默认 (0, 0)
        Point p2 = new Point(3, 4);
        System.out.println(p1);              // (0.0, 0.0)
        System.out.println(p2);              // (3.0, 4.0)
    }
}

规则:

3. 封装:private + getter/setter

面向对象三大特性之一封装:把字段声明为 private,通过 public 的 getter/setter 控制读写。这样可以加校验加日志改内部实现而不影响调用方

class Account {
    // 字段私有:外部不能直接访问,强制通过方法
    private String owner;
    private double balance;

    public Account(String owner, double balance) {
        this.owner = owner;
        // 通过 setter 钩子,在构造时也走校验
        setBalance(balance);
    }

    // getter:读字段
    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    // setter:写字段,可加校验
    public void setBalance(double balance) {
        if (balance < 0) {
            throw new IllegalArgumentException("余额不能为负");
        }
        this.balance = balance;
    }

    // 业务方法
    public void deposit(double amount) { balance += amount; }
}

public class EncapDemo {
    public static void main(String[] args) {
        Account acc = new Account("小明", 1000);
        // acc.balance = -100;            // ❌ 编译报错(private)
        acc.setBalance(500);              // ✅ 通过 setter 修改
        acc.deposit(200);
        System.out.println(acc.getBalance());    // 700.0
        // acc.setBalance(-1);            // ❌ 运行时抛 IllegalArgumentException
    }
}

Java 社区的最佳实践:字段默认 private,通过 getter/setter 暴露。虽然 IDE 能一键生成,显得啰嗦,但这是面向对象的基本修养

4. 访问修饰符

Java 有 4 种访问级别(从严到松):

经验法则:

5. static 静态成员

static 修饰的字段和方法属于类本身,而不是某个对象。所有对象共享一份静态变量,无需创建对象就能调用静态方法。

class Counter {
    // 静态变量:属于类,所有对象共享一份
    static int totalCount = 0;

    // 实例变量:每个对象独立一份
    int id;
    String name;

    public Counter(String name) {
        this.name = name;
        totalCount++;              // 每创建一个对象,共享计数器 +1
        this.id = totalCount;      // 用 totalCount 给对象分配唯一 id
    }

    // 静态方法:属于类,直接 类名.方法() 调用
    // 不能访问实例变量(没有 this)
    public static int getTotalCount() {
        return totalCount;
    }
}

public class StaticDemo {
    public static void main(String[] args) {
        new Counter("A");
        new Counter("B");
        new Counter("C");

        // 静态方法直接用类名调用
        System.out.println(Counter.getTotalCount());   // 3
        System.out.println("类被加载了");
    }
}

静态 vs 实例:

6. this 的三种用法

class Book {
    String title;
    double price;

    public Book(String title, double price) {
        // 1. this 区分字段和参数(最常见的用途)
        this.title = title;
        this.price = price;
    }

    public Book(String title) {
        // 2. this(...) 调用另一个构造方法,必须放第一行
        this(title, 0.0);
    }

    public Book setPrice(double price) {
        this.price = price;
        // 3. 返回 this,实现链式调用(fluent API)
        return this;
    }

    public Book setTitle(String title) {
        this.title = title;
        return this;
    }
}

public class ThisDemo {
    public static void main(String[] args) {
        Book b = new Book("Java").setPrice(99).setTitle("Java 17");
        // 链式调用:setPrice 返回 this,继续调 setTitle
        System.out.println(b.title + " " + b.price);
    }
}

总结 this 的三种用法:

7. 实战:简易 Book 类

把字段、构造、封装、static、方法综合起来,你能写出一个完整的 Book 类。试着在 IDE 里建一个 Book.java,把上面的代码贴进去,看看 IDEA 怎么生成 getter/setter(快捷键 Alt+Insert / mac Cmd+N)。

小结

这一章你掌握了 Java 面向对象的基础:类、对象、字段、方法、构造方法、this、封装、static、访问修饰符。理解了"图纸—实物"模型,你就理解了 Java 程序的基本组成。下一篇我们看 Java 继承——如何复用和扩展已有类。

← 上一篇 Java 字符串

下一篇 Java 继承

✈️💬