Java 关键字 final

一、final关键字的功能概述

final关键字可以用来修饰引用、方法和类。

1、用来修饰一个引用

  1. 如果引用为基本数据类型,则该引用为常量,该值无法修改;

  2. 如果引用为引用数据类型,比如对象、数组,则该对象、数组本身可以修改,但指向该对象或数组的地址的引用不能修改。

  3. 如果引用时类的成员变量,则必须当场赋值,否则编译会报错。

    例子如下所示:

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; transition-duration: 0.2s; transition-property: background-color, border-color, border-radius, padding, margin, color, opacity; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">final class Person {
String name ="zs";
//3. 此处不赋值会报错 //final int age;
final int age = 10;
} public class Demo01 { public static void main(String[] args) {
//1. 基本数组类型为常量,无法修改 final int i = 9; //i = 10;

    //2\. 地址不能修改,但是对象本身的属性可以修改
    Person p = new Person();
    p.name = "lisi"; final int[] arr = {1,2,3,45};
    arr[3] = 999; //arr = new int[]{1,4,56,78};

}
}</pre>

[
复制代码

](javascript:void(0); "复制代码")

2.用来修饰一个方法

当使用final修饰方法时,这个方法将成为最终方法,无法被子类重写。但是,该方法仍然可以被继承。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; transition-duration: 0.2s; transition-property: background-color, border-color, border-radius, padding, margin, color, opacity; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">class Person { public final void say() {
System.out.println("说....");
} public void eat() {
System.out.println("吃...");
}
} class Teacher extends Person { //1. final修饰的方法不能被重写,但此方法仍然被继承
/@Override
public void say() {
System.out.println("老师在一本正经的说...");
}
/

public void eat() {
    System.out.println("老师在大口大口的吃...");
}

} public class Demo02 { public static void main(String[] args) {
Teacher t = new Teacher();
t.say();
}
}</pre>

[
复制代码

](javascript:void(0); "复制代码")

3.用来修饰类

当用final修改类时,该类成为最终类,无法被继承。简称为“断子绝孙类”。

[
复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; transition-duration: 0.2s; transition-property: background-color, border-color, border-radius, padding, margin, color, opacity; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">/***

  • final用法3:修饰类,则该类成为最终类,无法被继承
  • @author Administrator
  • */
    final class Person02 { } //class Teacher02 extends Person02 { } //class MyString extends String{}
    public class Demo03 {

}</pre>

[
复制代码

](javascript:void(0); "复制代码")

比如常用的String类就是最终类。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容