2013-11-25 80 views
0

我在做,它的基本代碼如下的程序:Java:如何在同一個類的另一個方法中調用一個類的方法?

公共類StatisticalList擴展的ArrayList {

public double getMinimumValue() {...} 

    public double getMaximumValue() {...} 

    public double range(){ 

      double range = StatisticalList.getMaximumValue() - StatisticalList.getMinimumValue(); 

      return range; 
} 

在這我已經實現了兩個方法,getMinimumValue和getMaximumValue。接下來我想實現一個方法getRange。看起來很容易,不要再次進行計算,只需調用get__Value()方法即可。

但是,這給了錯誤的方法maxValue()未定義的類型ArrayList。我想在我的程序中需要多次使用其他方法中的方法時進行這種計算。我如何得到這個工作?

+0

由於方法不是靜態的,您可以直接調用它們,例如'getMaximumValue()' –

回答

3

您正在對StatisticalList上的靜態方法調用調用getMaximumValue()和getMinimumValue()。

double range = getMaximumValue() - getMinimumValue() 

應該讓你找到你想要的。

0

基本上語法StatisticalList.getMaximumValue()是用於調用靜態方法。

而您試圖調用的方法是instance方法。

所以,如果你想打電話給他們在同一類

double range = getMaximumValue() - getMinimumValue(); 

如果你想別的地方,你需要有StatisticalList

StatisticalList s = new StatisticalList(); 
double range = s.getMaximumValue() - s.getMinimumValue(); 
1

的方法的reference中定義的一些使用在這個班上任何地方都可以上課。而且,由於您使用了「公共」訪問修飾符,因此您的方法可以從包中的任何其他類訪問。然而,要在不同包中的類中訪問它們,則需要導入該類。請參閱文檔here以及訪問修飾符here

而且你還可以簡化您的範圍()方法:

public double range() { 
    return (getMaximumValue() - getMinimumValue()); 
} 
1

一言以蔽之:

double range = getMaximumValue() - getMinimumValue(); 

但是,讓我們解釋一下。首先,我不太確定這段代碼是如何編譯給你的。 以「classname.methodname」的形式調用方法適用於靜態方法,因此當您調用StatisticalList.getMaximumValue()時,java編譯器希望在那裏看到一個靜態方法。
我想你也想要它。您希望getMaximumValue找到ArrayList中的值中的最大值。所以你應該在「this」對象上調用這個方法。只需取下2×StatisticalList.從該行並將其如下:

double range = getMaximumValue() - getMinimumValue(); 

另外你還應該小心你如何實現get__Value()方法。 您的收藏延伸ArrayList,所以它基本上是ArrayList<Object> 它可以容納來自各種類型的物體。不僅數字。 更改類定義爲

public class StatisticalList extends ArrayList<Double> { 

可能會更有意義。

試一試..

相關問題