static關鍵字可用在變量、方法和內部類中。
在類的定義體中,方法的外部可包含static語句塊,在所屬的類被載入時執行一次,用于初始化static屬性,但不能初始化非靜態變量,類變量在整個類中共享。
如:
public class Count {
? private int serialNumber;
? public static int counter;
? static {
??? System.out.println("static自由塊被執行");?? //先執行靜態塊
??? counter = 1;
? }
? public static int getTotalCount() {
??? return counter;
? }
? public Count() {
??? counter++;
??? serialNumber=counter;
? }
? public static void main(String[] args)
? {
? ?System.out.println("main() invoked");
? ?System.out.println("counter = "+Count.counter);
??????? Count t=new Count();
??????? System.out.println("counter = "+Count.counter+" "+t.serialNumber);
? }
}
java.lang.Math是一個final類,不可被繼承,final變量是引用變量,則不可以改變它的引用對象,但可以改變對象的數據,final方法不可以被覆蓋,但可以被重載。
如:
class Aclass
{
?int a;
?//構造器
?public Aclass()
?{
??a = 100;
?}
?final public void paint(){
??System.out.println("55555555");
?}
?final public void paint(int i){
??System.out.println(i);
?}
?public void setA(int theA)
?{
??a = theA;
?}
?public int getA()
?{
??return a;
?}
}
//定義一個類來測試
public class TestFinal
{???????
?????? //如果final變量是引用變量,則不可以改變它的引用對象,但可以改變對象的數據
?final Aclass REF_VAR=new Aclass();
?public static void main(String[] args)
?{
??TestFinal tf = new TestFinal();
??tf.REF_VAR.setA(1);
??System.out.println(tf.REF_VAR.getA());
??tf.REF_VAR.paint();
??tf.REF_VAR.paint(1);
?}
}