理解java中的final关键字个人笔记

理解java中的final关键字

final用于声明属性,方法和类,分别表示属性不可改变,方法不可覆盖,类不可继承。

1,修饰类

当用final修饰一个类时,表明这个类永远不能被继承。
final类中的所有成员方法都会被隐式的指定为final方法

示例
public final class People {

}
//报错:The type Student cannot subclass the final class People
class Student extends People {

}

2.修饰方法

使用final修饰的方法, 代表这个方法不可以被子类的方法重写。

注:类的private方法会隐式地被指定为final方法
final方法在编译阶段绑定,称为静态绑定(static binding)。
final方法比非final方法要快,因为在编译的时候已经静态绑定了,不需要在运行时再动态绑定。

示例
public class Base {
    public final void outInfo() {
        System.out.println("我是final方法,不被继承类修改");
    }
}
class Demo extends Base {
    //错误提示: Cannot override the final method from Base
    public  void outInfo() {
        int num = 0;
        num++;
    }
    public void test() {
    }
}

3.修饰变量

对于一个final变量,如果是基本数据类型的变量,在其数值初始化之后便不能再更改;如果是引用类型的变量,在其初始化后便不能再让其指向另一个对象;(对于集合对象声明为final指的是引用不能被更改,但是你可以向其中增加,删除或者改变内容)

public final class FinalTest {

    private String name = "test";

    public static void main(String[] args) {
        final int num = 100;
        // 报错:The final local variable num cannot be assigned. It must be blank and not using a compound assignment
        // num = 10;

        FinalTest test = new FinalTest();
        test.name = "test1";

        final List list = new ArrayList();
        list.add("a");
        list.remove(0);

        //The final local variable list cannot be assigned. It must be blank and not using a compound assignment
        list = new LinkedList<>();
    }
}

final的好处:

将类、方法、变量声明为final能够提高性能,这样JVM就有机会进行估计,然后优化。

1) final关键字提高了性能。JVM和Java应用都会缓存final变量。
2) final变量可以安全的在多线程环境下进行共享,而不需要额外的同步开销。
3) final关键字,JVM会对方法、变量及类进行优化。

参照原文链接:

https://www.cnblogs.com/dolphin0520/p/3736238.html
http://www.importnew.com/7553.html
https://jingyan.baidu.com/article/597a064363b676312b5243ad.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值