Java学习笔记之final关键字

时间:2021-09-07 15:27:58

final:最终的,可以用来修饰类、属性、方法。

1、final修饰类:这个类不能被继承。如:String类、StringBuffer类、System类

2、final修饰方法:这个方法不能被重写。如Object类的getClass()

3、final修饰属性:此属性就一常量,一旦初始化就不能再赋值。习惯上用大写字母表示。如Math.PI




此常量的赋值:①该常量不能用默认初始化。②可以显示的赋值。代码块、构造器。

用static修饰的final变量:全局常量

下面是一个比较final与static final的区别的例子

class SelfCounter {
private static int counter;
private int id = counter++;

public String toString() {
return "SelfCounter :" + id;
}
}

class WithFinalFields {
static final SelfCounter wffs = new SelfCounter();
final SelfCounter wff = new SelfCounter();


public String toString() {
return "wff = " + wff + "\n wffs = " + wffs;
}
}

public class StaticFinal {
public static void main(String[] args) {
System.out.println("First Object :");
System.out.println(new WithFinalFields());
System.out.println("Second Object: ");
System.out.println(new WithFinalFields());
}
}