一、final关键字的作用
- final代表最终的意思,可以修饰成员方法、成员变量、类
二、final修饰类、方法、变量的效果
- final修饰类:该类不能被继承(可以有父类,不可有子类)
- final修饰方法:该方法不能被重写
- final修饰变量:表明该变量是一个常量,不能再次赋值
三、上案例
- 案例1
class Student {
final int A;
}
编译报错
没有默认值
- 案例2
class Student {
final int A = 10;
}
编译正确
- 案例3
class Student {
final int A = 20;
}
class Teacher {
final int A = 10;
}
class Demo {
public static void main(String[] args) {
System.out.println(A);
System.out.println(Student.A);
}
}
编译报错
①A不能被直接输出
②A被final修饰,不是被static修饰,所以不能用类名调用
- 案例4
class Student {
public final int a;
{
a = 20;
}
}
编译正确
构造代码块的应用
- 案例5
class Student {
public final int a = 10;
{
a = 20;
}
}
编译报错
final修饰的数据,只能赋值一次,而你赋值了两次
- 案例6
class Student {
public final int a;
static {
a = 20;
}
}
编译报错
因为静态代码块会优先执行,而在它执行的时候,a还没有去定义,当然会报错
- 案例7
class Student {
public static final int a;
static {
a = 20;
}
}
编译正确
- 案例8
class Student {
public static final int a;
{
a = 20;
}
}
编译报错
构造代码块只会在创建对象的时候执行,而static可以用类名使用
当被用作类名使用的时候,构造代码块还没有机会被执行,当然会报错
- 案例9
class Student {
public final int a;
public Student(){
a = 20;
}
}
编译正确
- 案例10
class Student {
public final int a;
{
a = 20;
}
public Student() {
a = 10;
}
}
编译报错
因为赋值了两次
- 案例11
class Student {
public final int a = 20;
public Student() {
a = 10;
}
}
编译报错
因为赋值了两次
- 案例12
class Student {
public final int a;
public Student(int age) {
a = age;
}
public Student() {
a = 10;
}
}
编译报错
因为赋值了两次
- 案例13
class Student {
public final int a;
public Student(int age) {
}
public Student() {
a = 10;
}
}
编译报错
明显我们调用Student有参构造的时候,a是没有赋值的
- 案例14
class Student {
public final int a;
{
a = 20;
}
public Studetn(int age) {
}
public Student() {
}
}
编译正确
- 案例15
class Student {
public final int a = 20;
public Student(int age) {
}
public Student() {
}
}
编译正确
- 案例16
class Student {
public final int a;
public Student(int age) {
a = 20;
}
public Student() {
this(10);
}
}
编译正确
哪怕调用无参构造,this也会去调用有参构造,所以无论如何a都是有值的