2017-09-16 107 views
0

所以我試圖製作一個Java GUI計算器,並開始懷疑在一個類擴展另一個類的場景中是否會有所不同,在擴展中調用super.functionname而不是隻調用functionname類。調用父構造函數Java

class frame extends JFrame{ 
     public buttonframe(){ 

     // any difference between this.add.. or super.add.. 

     } 
} 

然後,我做了幾個類試驗一點,我過來的東西,我不明白。

class A{ 
    public A(){ 
     System.out.println("A"); 
     h(); 
    } 

    public void h(){  
     String className = this.getClass().getName(); 
     System.out.println(className); 
    } 
} 

class B extends A{ 
    public B(){ 
     System.out.println("B"); 
     h(); 
    } 
} 

運行:

public static void main(String[] args){ 
    new A(); 
    new B(); 
} 

產生輸出:

> A calculator.A 
> A calculator.B 
> B calculator.B 

我知道,擴展的類會調用父類的構造函數,但爲什麼它產生的結果計算器.B(儘管我不知道爲什麼它必須這樣做,但我認爲A classname = new B();與它有關),而不是calculator.A當它是構造函數calle d從A類?

編輯:

class A{ 
public A(){ 
    //Can I instantiate a new B() and somehow ouput "A"? 
//I can do it using A.hs(); but can I do it: 

//Using the method h() but with a specific keyword infront of h() so 
//that it always refers to the method h() of the class A. 
h(); 
} 
public static void hs(){ 
System.out.println("A"); 
} 
    public void h(){ 
    System.out.println("A"); 
    } 
} 

class B extends A{ 
    public B(){ 
     h(); 
} 
    public void h(){ 
    System.out.println("B"); 
    } 
} 

回答

1

其結果是,因爲該語句的:

String className = this.getClass().getName(); 

時稱爲new B()當前對象(this)是B和因此的B類名。


所以,完整的序列,你的情況應該是:

A() => prints A => call h() with current object of 'A' => prints classname of A 

B() => calls super c'tor A() => prints A => call h() with object of 'B' 
    => prints classname of B => prints B => call h() => prints classname of B 
+1

這有一定道理,當我思考的問題。我意識到我最近並沒有「足夠的擴展類」,因爲每次使用this關鍵字時,它都只在同一個類中,所以我開始將此關鍵字與類關聯起來而不是對象本身。 –

+0

雖然有一點我很好奇。一個classname = new B(),其中函數h()在A構造函數中運行,並且都具有函數h(),其中類A打印A並且類B打印B.是否有關鍵字引用Ah()用在A的構造函數中?所以新的B()將輸出A.我不能使用這個,並且我不能在A()中使用super。我意識到我可以使用靜態函數,但這是我唯一能做的事情嗎?我對Java很新,但在Csharp方面有一些經驗。 –

+0

很不清楚,你剛剛問了什麼。如果您需要參考A或B的實例,您仍需要嘗試創建一個或使用該類的靜態引用。 – nullpointer