JavaSE进阶:final修饰符
发布日期:2021-04-30 21:10:40 浏览次数:99 分类:精选文章

本文共 2626 字,大约阅读时间需要 8 分钟。

Java中的final修饰符解析

final修饰符在Java中是一个强烈的修饰符,具有较高的限制性。本文将从多个方面分析final修饰符的用法及其相关问题。

一、final修饰的类无法继承

final修饰的类被称为最终类,其不能被其他类继承。这种限制是为了确保类的完整性和安全性。如果一个类被声明为final,任何其他类都无法继承它并覆盖其方法或重写其行为。

示例:

public class TestFinal {
public static void main(String[] args) {
// 无任何问题
}
}
final class TestA {
}
class TestB extends TestA {
}

运行时会报错:

The type TestB cannot subclass the final class TestA

错误提示:

final修饰的类无法被继承。因此,在类定义时务必慎重考虑是否使用final修饰。


二、final修饰的方法无法重写

final修饰的方法也无法被重写。这是因为final方法的定义本身就是最终的,不能被子类继承并修改其行为。

示例:

public class TestFinalMethod {
public static void main(String[] args) {
MethodB s1 = new MethodB();
s1.methodA();
}
}
class MethodA {
public final void methodA() {
System.out.println("-----A-----");
}
}
class MethodB extends MethodA {
public void methodA() {
System.out.println("-----B-----");
}
}

运行时会报错:

Exception:inthread "main" java.VerifyError:class MethodB overrides final method MethodA.method()V

错误提示:

final修饰的方法无法被重写。因此,在方法定义时务必慎重考虑是否使用final修饰。


三、final修饰的局部变量只能赋值一次

final修饰的局部变量只能在声明时赋值,之后不能再进行赋值。这是因为final变量需要保证其值的不变性。

示例:

public class TestFinal2 {
public static void main(String args[]) {
final int a;
a = 100;
final int b = 100;
b = 90;
}
}

运行时会报错:

The final local variable b cannot be assigned. It must be blank and not using a compound assignment

错误提示:

final修饰的变量只能赋值一次。因此,在使用final修饰局部变量时,需确保变量在声明时已经赋值。


四、final修饰的引用只能指向一个对象

final修饰的引用意味着该引用只能存储一个对象的地址,无法在运行时更改指向的对象。这种特性在内存管理中非常重要。

示例:

public class Test1 {
public static void main(String args[]) {
final Person p1 = new Person(30);
p1 = new Person(40);
System.out.println(p1.age);
}
}
class Person {
int age;
public Person() {
}
public Person(int age) {
this.age = age;
}
}

运行时会报错:

The final local variable p1 cannot be assigned. It must be blank and not using a compound assignment

错误提示:

final修饰的引用只能指向一个对象。因此,在引用前务必确保其已经存储了正确的对象地址。


五、final修饰的实例变量必须手动赋值

final修饰的实例变量需要在声明时手动赋值,否则会导致编译错误。

示例:

public class Test2 {
public static void main(String args[]) {
}
}
class Person2 {
final int a;
}

运行时会报错:

The blank final field a may not have been initialized

解决方法:

final int a = 10;

错误提示:

final修饰的实例变量必须手动赋值,否则会引发编译错误。


六、常量的定义

在五中,我们看到实例变量前面加入final后值不会发生变化,但实例变量在堆中占用内存。因此,我们可以通过在final修饰的实例变量前面加入static,使其变为常量,优化内存使用。

示例:

public class Test2 {
public static void main(String args[]) {
}
}
class Person2 {
static final int a = 10;
}

常量一般是公开的,因此常量一般写成:

public static final int a = 10;

总结:

final修饰符在Java中具有多种用法和限制。在类、方法、局部变量和引用等场景中,final修饰都有其特殊规则和限制。正确理解并遵守这些规则是编写高质量Java代码的关键。

上一篇:轻松解决Tomcat启动慢的问题,只需一行代码
下一篇:16 张图带你搞懂 Java 数据结构,从此想不飘都难!

发表评论

最新留言

很好
[***.229.124.182]2026年05月27日 17时08分48秒