Java基础-常用关键字 final

final关键字功能概述

final关键字可以修饰变量,方法和类

修饰变量

1、变量为基本数据类型,该变量为常量,该值无法修改

2、变量为引用数据类型,例如对象,数组,则该对象、数组本身可以修改,但是指向该对象或者数组的地址的引用不能修改

3、final修饰类的成员变量,必须当场赋值,否则编译会报错

 1 final class Student{
 2     String name = "Tom";
 3     final int age = 10;
 4 }
 5 public class Final {
 6     public static void main(String[] args) {
 7         final int i = 9;
 8         Student stu = new Student();
 9         stu.name = "lin";
10         
11         final int[]arr = {1,2,3,4};
12         arr[3] = 6;
13         
14     }
15 }

 

修饰方法

final修饰方法的时候,这个方法讲成为最终方法,无法被子类重写,但是,该方法可以被继承

 1 class Person {
 2     public final void say() {
 3         System.out.println("说....");
 4     }
 5     public void eat() {
 6         System.out.println("吃...");
 7     }
 8 }
 9 class Student extends Person {
10     //1. final修饰的方法不能被重写,但此方法仍然被继承
11     /*@Override
12     public void say() {
13         System.out.println("...");
14     }*/
15 
16     @Override
17     public void eat() {
18         System.out.println("eat...");
19     }
20 }
21 public class Final {
22     public static void main(String[] args) {
23         Student s = new Student();
24         s.say();
25     }
26 }

 

修饰类

当用final修饰类的时候,该类无法被继承。

1 final class Person02 { 
2     
3 }
4 
5 //class Test extends Person02{  //Cannot inherit from final 'com.study.test3.Person02'
6 //    
7 //}

 

posted @ 2021-09-23 17:43  r1-12king  阅读(39)  评论(0编辑  收藏  举报