2012-11-09 210 views
0

這個問題聽起來愚蠢到一些,但我需要得到它在我心裏清楚。動態綁定和靜態綁定

class J_SuperClass { 



void mb_method() { 
    System.out.println("J_SuperClass::mb_method"); 
    } 
    static void mb_methodStatic() { 
     System.out.println("J_SuperClass::mb_methodStatic"); 
    } 
} 
public class J_Test extends J_SuperClass { 
    void mb_method() { 
    System.out.println("J_Test::mb_method"); 
    } 
    static void mb_methodStatic() { 
    System.out.println("J_Test::mb_methodStatic"); 
    } 
    public static void main(String[] args) { 
    J_SuperClass a = new J_Test(); 
    a.mb_method(); 
    a.mb_methodStatic(); 
    J_Test b = new J_Test(); 
    b.mb_method(); 
    b.mb_methodStatic(); 
    } 
} 

輸出是:

J_Test::mb_method 
J_SuperClass::mb_methodStatic 
J_Test::mb_method 
J_Test::mb_methodStatic 

我知道動態綁定在運行時發生,靜態綁定發生在編譯時。此外,對於動態綁定,對象的實際類型決定調用哪種方法。所以我的問題是,在上面的代碼中,詞語「靜態」導致靜態結合,因此該對象的聲明的類型決定調用哪種方法?

+0

@ user1109363回覆:您的鹽漬問題,看看[這裏](http://stackoverflow.com/questions/12724935/salt-and-passwords)和[這裏](http://stackoverflow.com/questions/420843 /如何-做密碼 - 鹽 - 幫助 - 對-A-彩虹表攻擊) – StuartLC

回答

1

是的,static這個詞決定了靜態綁定,因爲在靜態方法中沒有多態性(因此需要動態綁定)。該方法被綁定到名稱,而不是到該類型,因爲它是與在該類名稱是唯一一個;它不與任何對象,因爲它是靜態的。

0

您可以嘗試反編譯J_Test類。你會看到:

public static void main(String args[]) 
    { 
     J_SuperClass a = new J_Test(); 
     a.mb_method(); 
     J_SuperClass.mb_methodStatic(); 
     J_Test b = new J_Test(); 
     b.mb_method(); 
     mb_methodStatic(); 
    } 

因此,超類的靜態方法是綁定的。