📚 Java 学习

4. 初始化与清理

构造器、static 与垃圾回收

构造器

创建对象时自动调用的方法,用来初始化对象。构造器名和类名完全相同,没有返回值。

public class Student {
    String name;
    int age;

    // 无参构造器
    public Student() {
        this.name = "未知";
        this.age = 0;
    }

    // 有参构造器(重载)
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Student s1 = new Student();              // 调无参
Student s2 = new Student("李雷", 20);    // 调有参

如果你不写任何构造器,Java 会自动给一个无参空构造器。一旦写了有参构造器,默认无参就消失了。

this 关键字

this 代表"当前对象"。在构造器中用来区分成员变量和参数:

public Student(String name) {
    this.name = name;  // this.name 是成员变量,name 是参数
}

this 也可以调用本类其他构造器:this(name, 20);,必须放在构造器第一行。

static 静态成员

static 修饰的属性/方法属于类,不属于对象。所有对象共享一份。

public class Counter {
    static int count = 0;   // 所有实例共享
    public Counter() { count++; }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count);  // 2

静态方法中不能直接访问非静态成员(因为没有 this)。main 方法就是 static 的。

final 关键字

final double PI = 3.14159;
// PI = 3.14;  // 编译错误

垃圾回收(GC)

Java 不需要手动 free/delete。JVM 自动回收没有引用指向的对象。

GC 的基本原理:可达性分析——从 GC Roots 出发,能到达的对象是存活的,不可达的就是垃圾。

Student s = new Student();
s = null;  // 切断引用,对象变成垃圾,等 GC 回收

你可以建议 GC:System.gc();,但不保证立刻执行。