谈谈我对java中final关键字的理解

JAVA 编程

final关键字

来源于有道词典的翻译:
final
adj. 最终的;决定性的;不可更改的;

作用

final可以用来修饰的结构:类,方法,变量

  1. final可以修饰一个类(例如:String类,System类,StringBuffer类)
  2. final用来修饰一个方法(例如:object类中的getclass())
  3. final用来修饰变量:此时变量为常量

final修饰属性可以考虑的位置有:显示初始化,代码中初始化,构造器初始化。

特点

  1. final修饰的类不能被继承(孤儿)
    final class A{};
    class B extends A{} //错误
  2. final修饰的方法不可被重写。
  3. final修饰的变量(属性和局部变量)不可再被赋值。

代码

final修饰属性:

final int age;//错误
final int age =10;//正确 显示初始化
final int num;
final int num01;
{
    num =10;//正确 代码块赋值
}
public finaltest(){
    num=10; //正确 构造器初始化
}
//方法中不能用final属性赋值
public void finaltest01(int num01){
    this.num01 = num01; //错误 
}

final修饰局部变量:

public class finaltest01 {
//   形参是变量只能在方法中使用此形参,但不能进行重新赋值。
    public static void see(final int num){
//        num=20;//报错
        System.out.println(num);
        final int i =3;//正确 常量不可变
    }
    public static void main(String[] args) {
        see(10);
    }
}

static final 关键字

用来修饰属性:全局常量

小练习(do exercise):

以下代码会报错吗?
评论区给出你的答案吧!

public class finaltest01 {
    public static void main(String[] args) {
        Student student = new Student();
        add(student);
    }
    public static void add(final Student m){
        m =new Student(); 
        m.id++; 
    }
    static class Student{
        public int id;
    }
}

答案参考:

public class finaltest01 {
    public static void main(String[] args) {
        Student student = new Student();
        add(student);
    }
    public static void add(final Student m){
//        m =new Student(); 错误 m对象不可变
        m.id++; //正确  对象并没有变,属性并没有用final修饰所以可变。
    }
    static class Student{
        public int id;
    }
}

以上就是我所总结的final关键字的用法及特点,欢迎各位交流评论!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Steve_hanhaiLong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值