标签:
package com.zyw.reusableClass; import java.util.Random; /** * Created by zyw on 2016/3/26. * from think in java * final数据 * 1.static final VALUE_THREE 做为编译期常量 大写字母命名,字与字下划线分开 * 2.不能因为数据为final就认为在编译时其值固定 * 3.final引用 表示引用不能指向新的对象 数组就是一种引用 */ public class FinalData { private static Random random=new Random(47);//private Random random=new Random(47); // Non-static field ‘random‘ cant be referenced from a static context private static final int VALUE_TWO=99; private static final int VALUE_THREE=39; public static final int i4= random.nextInt(20); static final int INT_5=random.nextInt(20); final int b=random.nextInt(); final Value value=new Value(11); private final int[] a={1,2,4,5}; public static void main(String args[]){ FinalData finalData=new FinalData(); FinalData finalData2=new FinalData(); finalData.value.i++; for(int i=0;i<finalData.a.length;i++){finalData.a[i]++;}//finalData.value=new Value(22); error System.out.println(FinalData.i4); System.out.println(FinalData.INT_5); System.out.println(finalData.a); System.out.println(finalData2.a); } } class Value{ int i; public Value(int i){this.i=i;} }
package com.zyw.reusableClass; /** * Created by zyw on 2016/3/26. * blank final 只要保证在使用前,被初始化即可 * 因此一个类的final域可以根据对象有所不同,又保持其恒定不变的特性 */ public class BlankFinal { private final Poppet p; public BlankFinal(int i) { this.p = new Poppet(i); } public static void main(String args[]){ BlankFinal blankFinal=new BlankFinal(10); System.out.println(blankFinal.p.toString()); } } class Poppet{ private int i; Poppet(int i){this.i=i;} public String toString(){return "poppet("+i+")";} }
package com.zyw.reusableClass; /** * Created by zyw on 2016/3/26. * 1.private 修饰类中方法隐式指定为final,此方法不需于基类接口的一部分 * ,仅是一些隐藏在类中的程序代码。 * 2.final 修饰方法,以防被继承覆盖。 * 3.final 修饰类 不允许被继承,最终类。 */ class WithFinals{ private final void f(){System.out.println("withFinal.f()");} private void g(){System.out.println("withFinal.g()");} } class OverridingPrivate extends WithFinals{ public final void f(){System.out.println("OverridingPrivate.f()");} public void g(){System.out.println("OverridingPrivate.g()");} } class OverridingPrivate2 extends OverridingPrivate{ // public final void f(){System.out.println("OverridingPrivate2.f()");} public final void g(){System.out.println("OverridingPrivate2.g()");} } public class FinalOverridingIllusion { public static void main(String args[]){ OverridingPrivate2 op2=new OverridingPrivate2(); op2.f(); op2.g(); OverridingPrivate op=op2; op.f(); WithFinals wf=op2; //wf.g(); } }
标签:
原文地址:http://www.cnblogs.com/yunwuzhan/p/5322976.html