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;
}
添加回答
举报