final 关键字

概述

final 关键字用于声明常量、防止继承和防止方法重写。

语法格式

final int CONSTANT = 100;              // 常量
public final class FinalClass { }      // 不可继承的类
public final void method() { }         // 不可重写的方法

基本用法

// final类 - 不能被继承
final class MathConstants {
    public static final double PI = 3.14159;
    public static final int MAX_SIZE = 100;
}

class Animal {
    // final方法 - 不能被重写
    public final void breathe() {
        System.out.println("呼吸");
    }

    public void makeSound() {
        System.out.println("发出声音");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("汪汪汪");
    }

    // public void breathe() { } // 错误:不能重写final方法
}

public class FinalExample {
    // final实例变量 - 必须初始化
    private final String name;

    public FinalExample(String name) {
        this.name = name; // 构造器中初始化
    }

    public void method() {
        // final局部变量
        final int count = 10;
        // count = 20; // 错误:不能修改final变量

        System.out.println("姓名:" + name);
        System.out.println("计数:" + count);
    }
}

常量定义

public class Constants {
    // 编译时常量
    public static final String APP_NAME = "我的应用";
    public static final int DEFAULT_SIZE = 100;

    // 运行时常量
    public static final long CURRENT_TIME = System.currentTimeMillis();

    private Constants() { } // 防止实例化
}

final关键字确保不可变性,是Java编程中重要的安全特性。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""