2012-05-28 18 views
0

我有一個被覆蓋的方法,在此方法中super用於調用被覆蓋的方法。然而,這個方法中的代碼是我在幾個類中使用的,我想通過將它們放到一個類中的單個方法中來重用此代碼。但由於此代碼使用關鍵字super,所以我不確定如何將重寫的方法的引用傳遞給我的新方法。例如,原來這裏是方法的Class1 INC:Java:將代碼移到另一個類後調用超級代碼

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    /* Lots of code goes here, followed by the super call */ 
    return super.onOptionsItemSelected(item); 
} 

在等級2:

public boolean onOptionsItemSelected(MenuItem item) 
{ 
    /* Code from class1 gets relocated here. But how do I call super on the original method? */ 

} 
+0

[代表](http://en.wikipedia.org/wiki/Delegation_pattern) – alphazero

回答

1

好,除非2級是你的1類的共同祖先,你不能用超級調用它。如果您將代碼移到另一個與繼承無關的類中,您將被迫使用對象組合,也就是說,您的類1(此處超級調用所在的地方)將需要對類2的對象引用(代碼已移至)對象以獲得對給定方法的訪問權限。

public boolean onOptionsItemSelected(MenuItem item) 
{ 
   /* Lots of code goes here, followed by the super call */ 
   return this.myRef.onOptionsItemSelected(item); 
} 

或者,你可以把有問題的方法靜態的,在它的情​​況下,你可以通過類訪問它暴露它(比方說,這就是所謂的使用率)。

public boolean onOptionsItemSelected(MenuItem item) 
    { 
       /* Lots of code goes here, followed by the super call */ 
       return Util.onOptionsItemSelected(item); 
    } 

取決於該方法的作用,但使其成爲靜態可能不是一個選項。

+0

「your cla爲了獲得對方法的訪問,ss 1將需要一個對象引用到一個class 2對象。「 - 但是我想要另一種方式。 Class2需要訪問class1中的方法。 – AndroidDev

+0

@AndroidDev在你的例子中,你的class1是在共同的祖先中調用super的那個。你將這個共同祖先的代碼移動到class2上,對吧? –

+0

是的。實際上,超級代碼在代碼中實際出現了很多次,但我保持簡單,只顯示一次。我不會從共同的祖先移動代碼。我將代碼從class1移動到class2。 onOptionsItemSelected仍然保留在class1中。 class1從其他類繼承。 – AndroidDev

0

您可以簡單地讓Class2擴展與Class1相同的類。

此答案的其餘部分假定Class1不從Class2繼承。

沒有進一步的情況下,很難說這是否是合適的,但你可以嘗試改變

public boolean onOptionsItemSelected(MenuItem item)

public static boolean onOptionsItemSelected(MenuItem item),並調用

YourClassName.onOptionsItemSelected(yourArgument)

+0

我沒有看到超級如何被稱爲任何。 – AndroidDev

+0

'super'可能無法按照您想要的方式使用。沒有您的示例的類層次結構很難說。沒有指定'Class1'和'Class2'是否擴展相同的類,或者'Class2'是否擴展'Class1',反之亦然。 –

相關問題