JAVA中final用法【20131205】

来源:互联网 发布:minix源码下载 编辑:程序博客网 时间:2024/05/16 09:49

一、final用法说明

final修饰变量:

对于final修饰的变量,表示该变量被赋予的引用是不可变的,可以理解为该变量只能指向一个地址,不能指向其它地址。

例如: final String tempS = "zhangs";  
       //这表示tempS只能指向zhangs,因为String是一个基本类型,其实tempS就相当于一个常量。
       final Date tempH = new Date() ; 
       //这表示tempH只能指向new出来的Date对象实例,不能指向其它处,此时tempH所指向的对象的值是可以通过调用对象的方法修改的,如setTime()方法。


final修饰参数:

对于final修饰的参数,表示对该参数只能引用,但不可以修改参数的值


import java.util.* ;public class Test15{public static void main(String[] args){    int testInt1 = 100 ;    int testInt2 = TempInt(testInt1);    System.out.println(testInt2);    Date testDate1 = new Date();    System.out.println(testDate1);    Date testDate2 = TempDate(testDate1);    System.out.println(testDate2);    Date testDate3 = TempDate1(testDate1);    System.out.println(testDate3);    System.out.println(testDate1);}static int TempInt(final int i){int s1 = i;//i++ ;   此处试图修改i的值,由于i是final类型的,编译的时候会报错return s1 ;};static Date TempDate (final Date tempH){Date tempH1 = tempH ;return tempH1;};static Date TempDate1 (final Date tempH){Date tempH1 = tempH ;tempH.setTime(100000);return tempH ;};}

final修饰方法:

对于final修饰的方法表示该方法不可以被子类重写,但可以被子类继承。


class ParentClass {      public final void TestFinal()     {          System.out.println("父类final方法");      }  }    public class ChildClass extends ParentClass {      //该处重写父类的TestFinal()方法,但由于父类的方法是final的,此处重写编译时会报错。    // public void TestFinal() {      // System.out.println("子类--重写final方法");      // }            public static void main(String[] args)     {          ChildClass sc = new ChildClass();          sc.TestFinal();      }  }

final修饰类:

对于final修饰的类表示该类不能再被其它类继承,例如String类就是final的,不能有其它类再继承String。