[英]Java: How to call method of a class in another method of the same class?
我正在編寫一個程序,其基本代碼如下:
公共類StatisticsList擴展ArrayList {
public double getMinimumValue() {...} public double getMaximumValue() {...} public double range(){ double range = StatisticalList.getMaximumValue() - StatisticalList.getMinimumValue(); return range; }
在此,我實現了兩種方法,getMinimumValue和getMaximumValue。 接下來,我要實現getRange方法。 似乎很容易不再執行計算,而只需調用get__Value()方法。
但這會導致錯誤。類型ArrayList的maxValue()方法未定義。 我想進行這種類型的計算,需要在程序中多次使用其他方法中的方法。 我該如何工作?
您正在作為統計方法列表上的靜態方法調用getMaximumValue()和getMinimumValue()。
double range = getMaximumValue() - getMinimumValue()
應該可以為您提供所需的東西。
簡而言之:
double range = getMaximumValue() - getMinimumValue();
但是,讓我們解釋一下。 首先,我不太確定這段代碼如何編譯。 以“ classname.methodname”形式調用方法是針對靜態方法的,因此,當您調用StatisticalList.getMaximumValue()
,Java編譯器希望在那里看到靜態方法。
我想您也想要它。 您希望getMaximumValue
在ArrayList
中的值中找到最大值。 因此,您應該在“ this”對象上調用此方法。 只需刪除2 x StatisticalList.
從此行開始,並如下所示:
double range = getMaximumValue() - getMinimumValue();
另外,您還應該注意如何實現get__Value()方法。 您的集合擴展了ArrayList
因此它基本上是ArrayList<Object>
,它可以容納所有類型的對象。 不僅數字。 將類定義更改為
public class StatisticalList extends ArrayList<Double> {
可能更有意義。
試試看..
基本上, StatisticalList.getMaximumValue()
語法用於調用靜態方法。
您嘗試調用的方法是instance
方法。
因此,如果您想在同一個班級中稱呼他們
double range = getMaximumValue() - getMinimumValue();
如果要在其他地方使用它,則需要reference
StatisticalList
StatisticalList s = new StatisticalList();
double range = s.getMaximumValue() - s.getMinimumValue();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.