`
aaron_ch
  • 浏览: 172815 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Final Usage

    博客分类:
  • Java
阅读更多
final在Java中并不常用,然而它却为我们提供了诸如在C语言中定义常量的功能,不仅如此,final还可以让你控制你的成员、方法或者是一个类是否可被覆写或继承等功能,这些特点使final在Java中拥有了一个不可或缺的地位,也是学习Java时必须要知道和掌握的关键字之一。
final成员
  当你在类中定义变量时,在其前面加上final关键字,那便是说,这个变量一旦被初始化便不可改变,这里不可改变的意思对基本类型来说是其值不可变,而对于对象变量来说其引用不可再变。其初始化可以在两个地方,一是其定义处,也就是说在final变量定义时直接给其赋值,二是在构造函数中。这两个地方只能选其一,要么在定义时给值,要么在构造函数中给值,不能同时既在定义时给了值,又在构造函数中给另外的值。下面这段代码演示了这一点:
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class Bat{
    final PI=3.14;          //在定义时便给址值
    final int i;            //因为要在构造函数中进行初始化,所以此处便不可再给值
    final List list;        //此变量也与上面的一样
    Bat(){
        i=100;
        list=new LinkedList();
    }
    Bat(int ii,List l){
        i=ii;
        list=l;
    }
    public static void main(String[] args){
        Bat b=new Bat();
        b.list.add(new Bat());
        //b.i=25;
        //b.list=new ArrayList();
        System.out.println("I="+b.i+" List Type:"+b.list.getClass());
        b=new Bat(23,new ArrayList());
        b.list.add(new Bat());
        System.out.println("I="+b.i+" List Type:"+b.list.getClass());
    }
}
此程序很简单的演示了final的常规用法。在这里使用在构造函数中进行初始化的方法,这使你有了一点灵活性。如Bat的两个重载构造函数所示,第一个缺省构造函数会为你提供默认的值,重载的那个构造函数会根据你所提供的值或类型为final变量初始化。然而有时你并不需要这种灵活性,你只需要在定义时便给定其值并永不变化,这时就不要再用这种方法。在main方法中有两行语句注释掉了,如果你去掉注释,程序便无法通过编译,这便是说,不论是i的值或是 list的类型,一旦初始化,确实无法再更改。然而b可以通过重新初始化来指定i的值或list的类型,输出结果中显示了这一点:
I=100 List Type:class java.util.LinkedList
I=23 List Type:class java.util.ArrayList
还有一种用法是定义方法中的参数为final,对于基本类型的变量,这样做并没有什么实际意义,因为基本类型的变量在调用方法时是传值的,也就是说你可以在方法中更改这个参数变量而不会影响到调用语句,然而对于对象变量,却显得很实用,因为对象变量在传递时是传递其引用,这样你在方法中对对象变量的修改也会影响到调用语句中的对象变量,当你在方法中不需要改变作为参数的对象变量时,明确使用final进行声明,会防止你无意的修改而影响到调用方法。
另外方法中的内部类在用到方法中的参变量时,此参变也必须声明为final才可使用,如下代码所示:
public class INClass{
   void innerClass(final String str){
        class IClass{
            IClass(){
                System.out.println(str);
            }
        }
        IClass ic=new IClass();
    }
  public static void main(String[] args){
      INClass inc=new INClass();
      inc.innerClass("Hello");
  }
}
final方法
将方法声明为final,那就说明你已经知道这个方法提供的功能已经满足你要求,不需要进行扩展,并且也不允许任何从此类继承的类来覆写这个方法,但是继承仍然可以继承这个方法,也就是说可以直接使用。另外有一种被称为inline的机制,它会使你在调用final方法时,直接将方法主体插入到调用处,而不是进行例行的方法调用,例如保存断点,压栈等,这样可能会使你的程序效率有所提高,然而当你的方法主体非常庞大时,或你在多处调用此方法,那么你的调用主体代码便会迅速膨胀,可能反而会影响效率,所以你要慎用final进行方法定义。
final类
  当你将final用于类身上时,你就需要仔细考虑,因为一个final类是无法被任何人继承的,那也就意味着此类在一个继承树中是一个叶子类,并且此类的设计已被认为很完美而不需要进行修改或扩展。对于final类中的成员,你可以定义其为final,也可以不是final。而对于方法,由于所属类为final的关系,自然也就成了 final型的。你也可以明确的给final类中的方法加上一个final,但这显然没有意义。
  下面的程序演示了final方法和final类的用法:
final class final{
    final String str="final Data";
    public String str1="non final data";
    final public void print(){
        System.out.println("final method.");
    }
    public void what(){
        System.out.println(str+"\n"+str1);
    }
}
public class FinalDemo {   //extends final 无法继承 
    public static void main(String[] args){
        final f=new final();
        f.what();
        f.print();
    }
}
  从程序中可以看出,final类与普通类的使用几乎没有差别,只是它失去了被继承的特性。final方法与非final方法的区别也很难从程序行看出,只是记住慎用。
final在设计模式中的应用
  在设计模式中有一种模式叫做不变模式,在Java中通过final关键字可以很容易的实现这个模式,在讲解final成员时用到的程序Bat.java就是一个不变模式的例子。如果你对此感兴趣,可以参考阎宏博士编写的《Java与模式》一书中的讲解。
  到此为止,this,static,super和final的使用已经说完了,如果你对这四个关键字已经能够大致说出它们的区别与用法,那便说明你基本已经掌握。然而,世界上的任何东西都不是完美无缺的,Java提供这四个关键字,给程序员的编程带来了很大的便利,但并不是说要让你到处使用,一旦达到滥用的程序,便适得其反,所以在使用时请一定要认真考虑。
分享到:
评论

相关推荐

    Android代码-利用三阶贝塞尔曲线模仿QQ空间直播页面右下角的礼物冒泡特效

    Usage 引入依赖 compile 'yasic.library.BubbleView:bubbleview:0.0.4' 启动动画 void startAnimation(final int rankWidth, final int rankHeight) void startAnimation(final int rankWidth, final int ...

    Crypto1Final-Bank:RPI 加密 I 类的最终项目

    Crypto1Final-Bank ##Protocol 所有传输都使用一个 AES256 加密数据块。 未加密的规范在 spec.txt 中。 ATM 向银行发送请求,银行处理交易并发送响应。 不接受乱序包。 要强制断开与服务器的连接,请发送事务号为 ...

    ukaip-2.70U3-final-vityan

    2.70U1 KOP(Operator): -Fixed: Enhanced and verified the "Automatic license update" pattern so ... -Fixed(Cosmetic): Changed the 'TOTURIAL' to 'TUTORIAL' in USAGE*.txt(Reported by ru-board user speedboy)

    Android代码-nopen

    Usage Java creates new types as open by default which can be dangerous. This checker ensures that the intent to leave a class open is explicitly declared. import com.jakewharton.nopen.annotation.Open;...

    Android代码-android-gpuimage

    GPUImage for Android Idea from: iOS GPUImage framework Goal is to have something as similar to GPUImage as possible. Vertex and fragment shaders are exactly the same....public void onCreate(final

    usage:用于命令行,Web和Flutter应用程序的Google Analytics(分析)包装

    Google Analytics(分析)的包装程序,用于命令行,Web和Flutter应用程序。 对于网络应用 ... final String UA = ...; Analytics ga = new AnalyticsIO ( UA , 'ga_test' , '3.0' , documentsDirectory

    Android代码-DebugLog

    DebugLog Create a simple and more understandable Android logs. Why? android.util.Log is the most usable library ...public static final String TAG = "MyApp or MyClass name"; void myFunc(){ android.util

    Fiori_Development_Guideline_Portal_V1.1 - Final Version.pdf

    Fortunately in the chapter Theming and CSS Usage you can see that SAPUI5 provides standard margins since version 1.28. The details how to use these standard margins are described on a separate Wiki ...

    Android代码-schematic

    Usage First create a class that contains the columns of a database table. public interface ListColumns { @DataType(INTEGER) @PrimaryKey @AutoIncrement String _ID = "_id"; @DataType(TEXT) @NotNull ...

    NIST SP800-73-2_part3_end-point-client-api-final.pdf

    FIPS 201 defines procedures for the PIV lifecycle activities including identity proofing, registration, PIV Card issuance, and PIV Card usage. FIPS 201 also specifies that the identity credentials ...

    Android代码-PinView

    PinView Provides a widget for enter PIN/OTP/password...final PinView pinView = findViewById(R.id.secondPinView); pinView.setTextColor( ResourcesCompat.getColor(getResources(), R.color.colorAccent, getTh

    Android代码-RecyclerViewCardGallery

    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.setAdapter...

    Android代码-Jounce

    Usage See the sample project for a comprehensive example. In a simple form, it looks a little something like this: long oneSecond = TimeUnit.SECONDS.toMillis(1); //Void, since we are not keeping track...

    Android代码-Android 按钮进度条效果

    ButtonProgressBar To get this Git project into your build: 1.Add this in your root build.gradle at the end of ...final ButtonProgressBar bar = (ButtonProgressBar) findViewById(R.id.bpb_main); bar.se

    I2 Localization.unitypackage

    FIX: To reduce memory usage, Term descriptions are now only used in the editor (not in the final build) If needed, use a disabled language to store it FIX: Inspector Width should now be detected more...

    WorkFlow:简化您在android中的方法耦合

    提高代码简洁性和可读性、降低维护成本Installation:dependencies { implementation 'com.qw:workflow:0.0.4'}Usage:场景示例1依次顺序的展示Toast,Dialog,SnackBar: private static final int STEP_TOAST = 1;...

    Color_descriptors

    descriptors that have been approved for the Final Committee Draft of the MPEG-7 standard. The color and texture descriptors that are described in this paper have undergone extensive evaluation and ...

    Pentaho_Data_Integration_4_Cookbook

    Pentaho_Data_Integration_4_Cookbook, ETL工具,In computing, extract, transform, load (ETL) refers to a process in database usage and especially in data warehousing. The ETL process became a popular ...

    The Definitive Guide to HTML5

    The final part of the book covers the associated W3C APIs that surround the HTML5 specification. You will achieve a thorough working knowledge of the Geolocation API, web storage, creating offline ...

    Android代码-ikvStockChart

    Features 当前最新版本:0.1.5 支持在 XML 布局文件和代码中设置各个线条颜色、大小配置 支持左滑、右滑加载 ...支持 fling 滑动 支持 MACD、RSI、KDJ、BOLL 四个... final EntrySet entrySet = new EntrySet(); entrySet

Global site tag (gtag.js) - Google Analytics