2 回答

TA貢獻1906條經驗 獲得超3個贊
你得到了
public static String getURL()
這意味著可以在不使用類實例的情況下調用此方法。因此,該方法中使用的所有內容也必須是靜態的(如果不作為參數傳遞)。
我只能假設緯度、經度或 appId 都不是靜態的。要么將它們設為靜態,要么static
從getUrl
.

TA貢獻1772條經驗 獲得超5個贊
假設latitudeandlongitude變量的聲明如下所示:
public class Locator{
private String latitude; //Notice this var is not static.
private String longitude; //Notice this var is not static.
}
并且您的目標是從另一個類中調用它,如下所示:
Locator loc = new Locator(someContext);
String url = loc.getURL();
那么你必須將該getURL方法聲明為非靜態的,這意味著它可以在一個變量上調用,并且它在內部用于組成 URL的latitude和變量是所述實例的變量。longitude所以像這樣聲明它:
public String getURL(){
return "api.openweathermap.org/data/2.5/weather?" +
"lat=" + latitude + //This instance's latitude
"&lon=" + longitude + //This instance's longitude
"APPID=" + APPID;
}
現在,另一方面,如果您打算這樣稱呼它:
Locator loc = new Locator(someContext);
String url = Locator.getURL(loc);
然后注意這里getURL是類的靜態方法,而不是類實例的方法。如果這是你的目標,那么聲明getURL如下:
public static String getURL(Locator loc){
return "api.openweathermap.org/data/2.5/weather?" +
"lat=" + loc.getLatitude() + //The latitude of instance loc
"&lon=" + loc.getLongitude() + //The longitude of instance loc
"APPID=" + APPID;
}
添加回答
舉報