java中非常重要的修飾詞---static、this、final、super
阿新 • • 發佈:2019-01-06
this
this總的來說表示指向當前物件的指標。就是說是哪個變數new了該物件就表示誰 this 還可以用於建構函式的呼叫,例如:上述程式碼構造2中的this(s) this不能和static同時使用,因為static修飾的方法和屬性歸類所有,而不是某個物件特有/** * * @ClassName: Test * @Description: this example * @author: Loser * @date:2016年9月12日 下午8:54:26 */ public class Test { private int i=0; //構造1 Test(int i){ this.i=i+1; //此時this表示引用成員變數i,而非函式引數i System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1)); } //構造2 Test(int i,int s){ this(s); //this呼叫第一個構造器,必須為於其第一行,構造方法也只能調 //用一個且僅一次構造器! System.out.println("Int constructor: "+i+"/n"+"String constructor: "+s); } public Test increment(){ this.i++; return this;//返回的是當前的物件 } public static void main(String[] args){ Test t1=new Test(10); Test t2=new Test(20,50); System.out.println(t1.increment().i); } }
super
super用於在子類中操作父類隱藏的屬性和方法 super在子類的建構函式中呼叫父類的建構函式,注意:super呼叫建構函式必須位於子類建構函式的第一條語句,因為構造順序為先構造父類的建構函式,再構造子類的建構函式,如果不位於第一條,那麼就違背了這原則,會報錯!static
static不能和this同時使用,因為static是供類所有,是所有物件共享的,類似全域性變數。首次載入類的時候就分配了記憶體,並且被static修飾的方法和變數JVM只加載一次。關於static訪問的誤區:
對於被static修飾方法的訪問是指方法本身外部的訪問。在上段程式碼中,關於static方法的訪問是指main之外的訪問,比如說:main方法無法訪問i,但是如果在main中例項化物件,通過物件去訪問物件裡面的變數是沒問題的,還有在main方法裡面可以宣告例項變數,例如j。記住:我們所說static修飾方法的訪問是它對於外部的訪問。public class TestStatic { private int i=0; public void increment(){ System.out.println("i="+i++); } public static void main(String[] args){ int j=10; Test t1=new Test(10); Test t2=new Test(20,50); j=t1.z; System.out.println(j); } }