`
bingtears
  • 浏览: 185741 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

static and final

    博客分类:
  • java
阅读更多
answers come from csdn:

static 静态的  就是不用创建对象就可直接类名+.访问

JVM装载一个类时,会先初始化static成员

final就是不能改变的  类或方法声明final时 表示不能被继承

final修饰的简单类型的变量,和对象类型的变量是不一样的

简单类型的值不可改变.

对象类型的引用一旦初始化后就不可改变.但是引用的事例的值可改变.

*******************************************************

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提供这四个关键字,给程序员的编程带来了很大的便利,但并不是说要让你到处使用,一旦达到滥用的程序,便适得其反,所以在使用时请一定要认真考虑。 
分享到:
评论

相关推荐

    static and final.

    static and final.

    echo public static final int BUFSIZE = 4096;

    public static final int SERVICE_PORT = 7; // Max size of packet, large enough for almost any client public static final int BUFSIZE = 4096; // Socket used for reading and writing UDP packets ...

    Swing 8种主流皮肤

    static final String Office2003 = "org.fife.plaf.Office2003.Office2003LookAndFeel"; static final String Minrodlf = "com.nilo.plaf.nimrod.NimRODLookAndFeel"; static final String A03Laf = "a03.swing....

    Android代码-Push

    With the Push Server OK, open the file Config.java and change the addresses of your server and the GCM Sender ID: public static class ADRESSES { public static final String SERVER_URL = ...

    MD5Code加密技术

    static final int S11 = 7; static final int S12 = 12; static final int S13 = 17; static final int S14 = 22; static final int S21 = 5; static final int S22 = 9; static final int S23 = 14; ...

    带注释的Bootstrap.java

    private static final Log log = LogFactory.getLog(Bootstrap.class); /** * Daemon object used by main. */ private static Bootstrap daemon = null; private static final File catalinaBaseFile; ...

    ssd教学辅导

    辅助完成ssd1 catfish作业 import java.util.Vector; 02./* 03. * Created on Jul 5, 2003 04. * 05. */ 06. 07./** 08. * Catfish - ...54. private static final int MIN_ENERGY_GROWTH_INCREMENT = 5

    android设置系统锁屏时间或屏保显示时间

    public static final String SCREEN_OFF_TIMEOUT = screen_off_timeout; private final int SCREEN_TIMEOUT_VALUE_NONE = Integer.MAX_VALUE;//永不休眠 private DreamBackend mBackend;//屏保管理类 @Override ...

    Data Visualization with Python and JavaScript

    You'll also receive updates when significant changes are made, new chapters are available, and the final ebook bundle is released., Python and Javascript are the perfect complement for turning data ...

    PowerMock资料大全(E文)

    PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more....

    Implementing Cloud Design Patterns for AWS(PACKT,2015)

    Following this, the book will discuss patterns for processing static and dynamic data and patterns for uploading data. The book will then dive into patterns for databases and data processing. In the ...

    C# 6 and .NET Core 1.0: Modern Cross-Platform Development

    The final section will demonstrate the major types of applications that you can build and deploy cross-device and cross-platform. In this section, we'll cover Universal Windows Platform (UWP) apps, ...

    RStudio for R Statistical Computing Cookbook(PACKT,2016)

    In the final few chapters, you’ll learn how to create reports from your analytical application with the full range of static and dynamic reporting tools that are available in RStudio so that you can...

    android暂停或停止其他音乐播放器的播放实现代码

    代码如下: 代码如下: public static final String PLAYSTATE_CHANGED = “com.android.music.playstatechanged”; public static final String META_CHANGED = ... public static final String PLAYBACK_CO

    learning unreal engine game development

    Chapter 1, An Overview of Unreal Engine, covers introductory content ...Chapter 7, Terrain and Cinematics, shows you how to add the final touches to your level using terrain manipulation and cinematics.

    Implementing.Cloud.Design.Patterns.for.AWS.1782177345

    In the final leg of your journey, you will get to grips with advanced patterns on Operations and Networking and also get acquainted with Throw-away Environments. Table of Contents Chapter 1: ...

    AJAX and PHP.pdf

    instance, and static class members in JavaScript, what the JavaScript execution context is, how to implement inheritance by using constructor functions and prototyping, and the basics of JSON. ...

    RStudio.for.R.Statistical.Computing.Cookbook

    In the final few chapters, you'll learn how to create reports from your analytical application with the full range of static and dynamic reporting tools that are available in RStudio so that you can ...

    CryEngine Game Development Blueprints(PACKT,2015)

    You will also explore how to get a static model from Maya and shaders setbup in the SDK to check the textures during creation, and create all the necessary engine files to export and see the game ...

Global site tag (gtag.js) - Google Analytics