java中幾個關鍵字 this static final

1.this
站在巨人肩膀上:
http://blog.csdn.net/fzfengzhi/article/details/2174406
http://blog.csdn.net/zhandoushi1982/article/details/5445314
用法1:
this是指向調用對象本身的引用名
下面的程序,第14行用TestThis(int i)這個構造器創建一個TestThis對象aa。
然後打印出: this i = 1, local i = 10
this.i就表示aa.i 即對象的實例域1
而local i表示局部變量i, 即傳遞進來的參數10
用法2:
this可以調用該類的其他構造器
第15行程序用TestThis(int i, String s)這個構造器創建一個TestThis對象bb。
第10行程序,this(i) 調用了構造器TestThis(i), 此時調用再次第6行程序。
打印出:this i = 1, local i = 20
this.i表示bb.i
local i 表示局部變量i, 即傳遞進來的參數20
接下來執行11行程序,打印出:secondconstructor i = 20

  1 public class TestThis
  2 {
  3         private int i = 1;
  4         public TestThis(int i)
  5         {
  6                 System.out.println("this i = " + this.i + ", local i = " + i    );  //改行會調用兩次,第一次對象是aa, 在創建時執行。第二次對象時bb, 在執行this(i)時執行。
  7         }
  8         public TestThis(int i, String s)
  9         {
 10                 this(i);  //調用構造器 TestThis(int i)
 11                 System.out.println("second constructor i = " + i);
 12         }
 13         public static void main(String[] args) {
 14                 TestThis aa = new TestThis(10);
 15                 TestThis bb = new TestThis(20, " second constructor");
 16         }
 17 }

2.static
站在巨人的肩膀上:
http://blog.csdn.net/zhandoushi1982/article/details/8453522
用法1: static修飾類中的實例域,稱爲靜態變量或類變量
特性:該類的所有對象共享該靜態變量

 public class TestStatic {
    private int instanceVarible = 1;
    private static int staticVarible = 1;
    public static void main(String[] args)
    {
        TestStatic testStaticA = new TestStatic();
        TestStatic testStaticB = new TestStatic();
        System.out.println("A 的實例變量爲" + testStaticA.instanceReturn());
        System.out.println("B 的實例變量爲" + testStaticB.instanceReturn());
        System.out.println("A 的靜態變量爲" + testStaticA.staticReturn());
        System.out.println("B 的靜態變量爲" + testStaticB.staticReturn());
    }
    public int instanceReturn()
    {
        return this.instanceVarible += this.instanceVarible;
    }
    public int staticReturn()
    {
        return this.staticVarible += this.staticVarible;
    }
}

輸出:
A 的實例變量爲2
B 的實例變量爲2
A 的靜態變量爲2
B 的靜態變量爲4
由於類testStaticA和testStaticB共享一個靜態變量staticVarible,在第一次返回靜態變量時testStaticA類把staticVarible改爲1+1=2; 第二次返回靜態變量時testStaticB類把staticVarible改爲2+2=4。

直接用 類名.靜態方法名 或者 類名.靜態變量名 就可引用並且直接可以修改其屬性值,不用get和set方法。上面的程序中staticReturn()是沒有必要的。
靜態對象 非靜態對象
擁有屬性: 是類共同擁有的 是類各對象獨立擁有的
內存分配: 內存空間上是固定的 空間在各個附屬類裏面分配
分配順序: 先分配靜態對象的空間 繼而再對非靜態對象分配空間

3.final
站在巨人的肩膀上:
http://blog.csdn.net/zhandoushi1982/article/details/5462387
Java關鍵字final有“這是無法改變的”或者“終態的”含義,它可以修飾非抽象類、非抽象類成員方法。

(1)final類不能被繼承,沒有子類,final類中的方法默認是final的。
(2)final方法不能被子類的方法覆蓋,但可以被繼承。
(3)final成員變量表示常量,只能被賦值一次,賦值後值不再改變。
(4)final不能用於修飾構造方法。
注意:父類的private成員方法是不能被子類繼承的,更不存在被覆蓋,因此private類型的方法默認是final類型的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章