大数据Java基础系列-final关键字

来源:互联网 发布:shadowsockx for mac 编辑:程序博客网 时间:2024/04/30 05:20

Java关键字final有“这是无法改变的”或者“终态的”含义,它可以用来修饰类、方法和变量。
(1)使用final修饰类,类就不可以被继承。如:

final class Father{    void talk(){        System.out.println("father talk ...");    }}class Son extends Father{}

在main方法中调用:
new Son();
编译时就会报错,如过强制运行,则会出现以下错误:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The type Son cannot subclass the final class Father
所以,如果希望类中的实现细节不被修改,并确定这个类不会扩展时,可以使用final来修饰这个类。常用的String类就是用final修饰的。
(2)使用final修饰的方法,不可以被覆盖。

class Father{    final void talk(){        System.out.println("father talk ...");    }}class Son extends Father{    void talk(){        System.out.println("son talk ...");    }}

在main方法中调用:
new Son().talk();
编译时就会报错,如过强制运行,则会出现以下错误:
Exception in thread “main” java.lang.VerifyError: class *.Son overrides final method talk.()V
如果在一个类中,希望锁定某些方法,不让任何继承类修改它的实现,就可以使用final来修饰这些方法。
(3)使用final修饰一个变量,那么这个变量只能被赋值一次。

class Son extends Father{    final int num = 30;    void talk(){        num = 20;        System.out.println("son talk ...");    }}

在main方法中调用:
new Son().talk();
编译时就会报错,如过强制运行,则会出现以下错误:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The final field Son.num cannot be assigned
使用final修饰的变量,一定是成员变量,一旦给定值,就不能再修改。如果某些变量的值是固定的,就可以使用final来修饰。

0 0