final关键字的作用
final主要起修饰作用,可以修饰类、属性(变量)、方法。
- 被修饰的类无法被继承
- 被修饰的属性无法被修改(属性为基本数据类型,则为常量;为引用数据类型,比如对象、数组,则该对象、数组中的值可以改变,但是引用地址不能改变)
- 被修饰的方法无法被重写
修饰类
// 父类使用final修饰
public final class Father {
}
// 子类继承会报错
class Son extends Father {
}
总结:如果不想类被继承重写,则使用final关键字修饰
修饰属性
被final
修饰的属性必须直接实例化(赋值)或者在构造函数中实例化(赋值),否则会报错
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getter/setter省略
}
public class Father {
// 被final修饰的基本数据类型则为常量
private final int a = 1;
// 被final修饰的对象,引用地址不可变
private final String str;
// 一般不用final修饰数组
private final int[] arr;
// 对象
private final Student student = new Student(1, "www", 12);
public Father(String str) {
this.str = str;
this.arr = new int[]{1, 2, 3};
}
}
public static void main(String[] args) {
Father father = new Father("123");
System.out.println(father.student);
father.student.setName("qqqq");
System.out.println(father.student);
System.out.println(father.student.getName());
// 这里报错,Cannot assign a value to final variable 'student'
father.student = new Student(2, "eee", 4);
}
结果:
com.test3.Student@1b6d3586
com.test3.Student@1b6d3586
qqqq
从结果可以看出,引用对象的内容可以改变,但是引用地址不变。
总结:一般常量我们会使用final修饰,防止被修改。使用匿名内部类时,经常会使用到final关键字,保证引用对象的地址不可变
修饰方法
被final
修饰的方法不能被重写,但是仍可以被子类继承
public final void eat(String food) {
}
总结:方法不想被重写则使用final
修饰
知识点
1、被final修饰的方法,JVM会尝试为之寻求内联,这对于提升Java的效率是非常重要的。因此,假如能确定方法不会被继承,那么尽量将方法定义为final的
2、被final修饰的常量,在编译阶段会存入调用类的常量池中