- 1 final:adj. 最终的;决定性的;不可更改的
- 2 final关键字可以修饰类、成员变量、成员方法
- final关键字修饰类,该类不能被继承
- final关键字修饰变量,该变量就变成了常量,只能被赋值一次
- final关键字修饰方法,该方法不能被重写(override)
- 3 final关键字注意事项
- 3.1 修饰基本数据类型
- 代码Demo如下
- 3.1 修饰基本数据类型
class StudentDemo{
public static void main(String[] args) {
int num1 = 10;
final int num2 = 20;
System.out.println("num1 is "+num1);
System.out.println("num2 is "+num2);
System.out.println();
num1 = 100;
//num2 = 200;//如果修改num2,编译会出错,通不过
System.out.println("num1 is "+num1);
System.out.println("num2 is "+num2);
}
}
运行结果:
num1 is 10
num2 is 20
num1 is 100
num2 is 20
可以看出,final修饰的基本数据类型,该变量是不能再改变的了
- 3.1 修饰引用数据类型
代码Demo如下:
错误代码:
class Student{
int age = 10;
final int age2 = 28; //can not be changed
public Student(){}
public void show(){
System.out.println("Age is "+ age);
}
}
class FinalDemo3{
public static void main(String[] args) {
final Student s1 = new Student();
s1.age = 11;
s1.show();
Student s2 = new Student();
s2.age = 12;
s2.show();
s1 = s2; //this line must be commented out.
}
}
运行结果:
FinalDemo3.java:20: 错误: 无法为最终变量s1分配值
s1 = s2; //this line must be commented out.
^
1 个错误
正确代码:
class Student{
int age = 10;
final int age2 = 28; //can not be changed
public Student(){}
public void show(){
System.out.println("Age is "+ age);
}
}
class FinalDemo3{
public static void main(String[] args) {
final Student s1 = new Student();
s1.age = 11;
s1.show();
Student s2 = new Student();
s2.age = 12;
s2.show();
//s1 = s2; //this line must be commented out.
}
}
运行结果:
Age is 11
Age is 12
可以看出,final修饰引用数据类型(代码中的s1)时。不能改变的是其地址值(所以s1 = s2;这句话是错误的),但是其地址值所指向的数据是可以改变的(s1.age = 11;)。
- 4 final修饰变量的初始化时机
对3中的class Student进行反编译:
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name: FinalDemo3.java
import java.io.PrintStream;
class Student
{
int age;
final int age2 = 28;
public Student()
{
age = 10;
}
public void show()
{
System.out.println((new StringBuilder()).append("Age is ").append(age).toString());
}
}
可以看出,final修饰的变量是在对象构造完成之前进行的