final关键字:通常指无法改变的,可能使用的场景有三种:数据、方法和类。
1、final修饰的类
当用final修饰类时,表名这个类不能被继承
验证
继承时报错 The type person cannot subclass the final class Student
2、final修饰的方法
1、防止在继承时方法被覆盖。
2、提升效率(在使用hotspot技术之后,Java虚拟机不再需要使用final方法进行优化,虚拟机可以探测不合理的内嵌调用因此不推荐使用final进行性能优化)
注:final类中的所有方法都隐式的指向指定为final
3、final修饰的数据
分为基础类型的变量和指定类型的变量
基础类型变量报错信息为:
The final field Student.num cannot be assigned
引用类型变量的报错信息为:
The final local variable obj cannot be assigned. It must be blank and not using a compound assignment
4、总结
1) final类不能被继承
2)final方法不能被子类的方法覆盖
3)final变量只能被赋值一次,赋值后值无法改变