作用
1、修饰变量:被final修饰的变量是不能被重新赋值的。
public class Demo {
public static final int num = 15;
public static void main(String[] args) {
// num = 20; 报错
}
}
2、修饰对象的引用:能通过函数赋值,但不能改变对象的引用。
public class Demo {
public static void main(String[] args) {
final People p = new People(); // final修饰
p.set(15); // 可以通过调用函数赋值
// p = new People(); 报错
}
}
class People {
private int num;
public void set(int num) {
this.num = num;
}
}
3、修饰方法:被final修饰的方法不能被子类重写。
class Parent {
public final void show() {
System.out.println("Parent show");
}
}
class Child extends Parent {
public void show() { // 报错
System.out.println("Child show");
}
}
4、修饰类:如果某个类被final修饰,那么这个类是不能被继承的。
final class Parent {
public final void show() {
System.out.println("Parent show");
}
}
class Child extends Parent { // 报错
}
使用final关键字的好处
1、JVM和Java应用都会缓存final变量,提高了性能。
2、使用final关键字,JVM会对方法、变量以及类进行优化。
3、final修饰的变量、类可以安全的在多线程环境下进行共享,而不需要额外的同步开销。