`
javasogo
  • 浏览: 1775421 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

浅谈Java中final,finalized,finally

阅读更多
final: final可以让你控制你的成员、方法或者是一个类是否可被覆写或继承等功能,这些特点使final在Java中拥有了一个不可或缺的地位,也是学习Java时必须要知道和掌握的关键字之一。 final成员 当你在类中定义变量时,在其前面加上final关键字,那便是说,这个变量一旦被初始化便不可改变,这里不可改变的意思对基本类型来说是其值不可变,而对于对象变量来说其引用不可再变。其初始化可以在两个地方,一是其定义处,二是在构造函数中,两者只能选其一。 下面程序很简单的演示了final的常规用法: publicclassTest{ finalintt=1;//在定义时给值 //或者(两者只能选其一) finalintt; publicTest(){ t=3;//构造时给值 } } 还有一种用法是定义方法中的参数为final,对于基本类型的变量,这样做并没有什么实际意义,因为基本类型的变量在调用方法时是传值的,也就是说你可以在方法中更改这个参数变量而不会影响到调用语句,然而对于对象变量,却显得很实用,因为对象变量在传递时是传递其引用,这样你在方法中对对象变量的修改也会影响到调用语句中的对象变量,当你在方法中不需要改变作为参数的对象变量时,明确使用final进行声明,会防止你无意的修改而影响到调用方法。 另外方法中的内部类在用到方法中的参变量时,此参变也必须声明为final才可使用,如下代码所示: publicclassTest{ voidprint(finalStringstr){ classInnerTest{ InnerTest(){ System.out.println(str); } } InnerTestit=newInnerTest(); } publicstaticvoidmain(String[]args){ Testtest=newTest(); test.print("Helloword!!!"); } } final方法 将方法声明为final那有两个原因,第一就是说明你已经知道这个方法提供的功能已经满足你要求,不需要进行扩展,并且也不允许任何从此类继承的类来覆写这个方法,但是继承仍然可以继承这个方法,也就是说可以直接使用。第二就是允许编译器将所有对此方法的调用转化为inline(行内)调用的机制,它会使你在调用final方法时,直接将方法主体插入到调用处,而不是进行例行的方法调用,例如保存断点,压栈等,这样可能会使你的程序效率有所提高,然而当你的方法主体非常庞大时,或你在多处调用此方法,那么你的调用主体代码便会迅速膨胀,可能反而会影响效率,所以你要慎用final进行方法定义。 final类 当你将final用于类身上时,你就需要仔细考虑,因为一个final类是无法被任何人继承的,那也就意味着此类在一个继承树中是一个叶子类,并且此类的设计已被认为很完美而不需要进行修改或扩展。对于final类中的成员,你可以定义其为final,也可以不是final。而对于方法,由于所属类为final的关系,自然也就成了final型的。你也可以明确的给final类中的方法加上一个final,但这显然没有意义。 finally: finally关键字是对Java异常处理模型的最佳补充。finally结构使代码总会执行,而不管有无异常发生。使用finally可以维护对象的内部状态,并可以清理非内存资源。如果没有finally,您的代码就会很费解。例如,下面的代码说明,在不使用finally的情况下您如何编写代码来释放非内存资源: publicvoidwriteFile(StringfilePath,StringfileName,Stringargs) throwsIOException { FileWriterfw=newFileWriter(filePath+fileName); try{ fw.write(args); }catch(IOExceptione){ //1 fw.close(); throwe; } //2 fw.close(); } 这段代码创建了一个FileWriterobject,并调用write方法。在退出该方法之前,您必须关闭FileWriterobject,以避免资源漏洞。为了完成这一任务,我们在//2处调用close,它是该方法的最后一条语句。但是,如果try块中发生一个异常会怎么样呢?在这种情况下,//2处的close调用永远不会发生。因此,您必须捕获这个异常,并在重新发出这个异常之前在//1处插入对close的另一个调用。这样就可以确保在退出该方法之前关闭FileWriterobject。这样编写代码既麻烦又易于出错,但在没有finally的情况下这是必不可少的。有了finally,前面的代码就可以重写为以下的形式: publicvoidwriteFile(StringfilePath,StringfileName,Stringargs) throwsIOException { FileWriterfw=newFileWriter(filePath+fileName); try{ fw.write(args); }catch(IOExceptione){ throwe; }finally{ fw.close(); } } finally块确保close方法总被执行,而不管try块内是否发出异常。因此,可以确保在退出该方法之前总会调用close方法。这样您就可以确信FileWriterobject被关闭并且您没有泄漏资源。 finalize:   根据Java语言规范,JVM保证调用finalize函数之前,这个对象是不可达的,但是JVM不保证这个函数一定会被调用。另外,规范还保证finalize函数最多运行一次。   通常,finalize用于一些不容易控制、并且非常重要资源的释放,例如一些I/O的操作,数据的连接。这些资源的释放对整个应用程序是非常关键的。在这种情况下,程序员应该以通过程序本身管理(包括释放)这些资源为主,以finalize函数释放资源方式为辅,形成一种双保险的管理机制,而不应该仅仅依靠finalize来释放资源。
分享到:
评论

相关推荐

    详解Java编程中final,finalize,finally的区别

    主要介绍了详解Java编程中final,finalize,finally的区别,这个在Java面试题中简直是太常见了...需要的朋友可以参考下

    finalized_model.sav

    finalized_model.sav

    Learn.Java.for.Android.Development_Apress.2010+src

    The book also briefly presents most (if not all) of Java version 7''s language features, although not much is said about closures or modules (which were not finalized at the time of writing). Java ...

    Programming In Lua First Edition(Finalized Revision 2.0) - PDF

    关键字:Programming In Lua、Lua程序设计、Finalized Revision 2.0 译序 作为脚本语言,Lua以其简洁优雅著称,对ANSI C标准的遵循令其具有很好的可移植性,并能高效地运行于各操作系统平台。与其他脚本语言不同,...

    Programming In Lua First Edition(Finalized Revision 2.0) - 7Z

    关键字:Programming In Lua、Lua程序设计、Finalized Revision 2.0 译序 作为脚本语言,Lua以其简洁优雅著称,对ANSI C标准的遵循令其具有很好的可移植性,并能高效地运行于各操作系统平台。与其他脚本语言不同,...

    OFR-Application-Finalized

    OFR-应用程序最终化

    爬虫代码matlab-CS388Mooney-project:CS388Mooney-project

    爬虫代码matlab ...final2.pdf for the finalized version data/src -> the source code we wrote for this project, which is explained below 履带式 /src/crawler -> Java code used to scrape down the paten

    delphi反编译工具 Decompiler v1.1.0.194

    commented ASM code with references to strings, imported function calls, classes methods calls, components in the unit, Try-Except and Try-Finally blocks. Note, this is a rewrite of the original DeDe....

    matlab设置画布大小代码-node-jspsych-base:mTurkTongLab应用程序的Node.js实现

    final sequence set 1. motor practice 2. randomly generated practice (2 items) 3. pregenerated practice (6 items) 4. pregenerated experiment trials - added subject information section - added post-...

    A Technical Overview of VP9--the Latest Open-Source Video Codec

    Google has recently finalized a next generation open-source video codec called VP9, as part of the libvpx repository of the WebM project (http://www.webmproject.org/). Starting from the VP8 video ...

    DbfDotNet_version_1.0_Source

    This article is also a work in progress please bookmark and come back later, if you want to see the final article. Why an embedded database Although most of us will use a SQL Server to store and ...

    ScoSocket.rar_The Risk

    The Android Bluetooth API is not finalized, and will change. Use at your own risk.

    3GPP 5G security

    As it is being finalized, the specification is stable enough to allow giving an overview. This paper presents the security aspects of the 5G system specified by the 3rd Generation Partnership Project...

    Android代码-RxJava3 预览版 Demo

    Version 3 development will be branched off of 2.x sometime after 2.2 has been finalized in the main RxJava repository. Preview for version 3 of RxJava, the modern ReactiveX style library for ...

    IGRF-12 coefficients 世界地磁场模型

    The coefficients for this degree and order 13 main field model were finalized by a task force of IAGA in December 2014. The IGRF is the product of a collaborative effort between magnetic field ...

    MobileWebServer_Book

    The reason behind these two largely similar products is that Raccoon is a development version under constant revision and without a finalized product-like state. The former product, although based ...

    matching_contracts

    它的工作方式如下: 在匹配回合中,部署此合同的新实例一旦回合完成,Gitcoin将计算每笔赠款获得的最终比赛金额在多次交易过程中,合同所有者将设置存储在payouts变量中的payouts映射。 这会将每个赠款接收地址映射...

    The C Programming Language_English Version

    Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, ...

    C Programming Language (2nd Edition)

    Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, ...

    MPEG-4 Standard

    MPEG-4, with formal as its ISO/IEC designation 'ISO/IEC 14496', was finalized in October 1998 and became an International Standard in the first months of 1999. The fully backward compatible ...

Global site tag (gtag.js) - Google Analytics