英文:
call non-static methods without creating an object in the same class in Java
问题
我明白如果我需要在类外部调用getItemList
,而不使用对象,我需要将该方法声明为公共的和静态的。我困惑的是类内部的情况。
在下面的代码中,我能否在不创建GitHubClient
对象的情况下调用getItemList
方法?如果我想直接调用getItemList
方法,是否应该将该方法声明为静态的?
public class GitHubClient {
private String s1 = "abc";
public List<Item> search(double lat, double lon, String keyword) {
// 省略使用 GitHub 客户端请求信息的代码
String responseBody = EntityUtils.toString(entity);
JSONArray array = new JSONArray(responseBody);
// 我是否能在没有对象的情况下调用这个方法
return getItemList(array);
}
private List<Item> getItemList(JSONArray array) {
// 用于过滤搜索结果的辅助函数
}
}
英文:
I understood that if I need to call getItemList
ouside the class without an object, I need to make the method public and static. What I am confused about is the case inside the class.
In the following code, can I call getItemList
method without creating a GitHubClient
object? If I want to call getItemList
method directly, should I make the method static?
public class GitHubClient {
private String s1 = "abc"
public List<Item> search(double lat, double lon, String keyword) {
// omit code using GitHub client to request info
String responseBody = EntityUtils.toString(entity);
JSONArray array = new JSONArray(responseBody);
// can I call the method without an object
return getItemList(array);
}
private List<Item> getItemList(JSONArray array) {
// helper function to filter the search result
}
}
</details>
# 答案1
**得分**: 0
是的,如果你希望能够在不创建对象的情况下从`GithubClient`外部调用`getItemList(JSONArray)`,你需要将其设为`public`和`static`。
基本上,就是这样:`public static List<Item> getItemList(JSONArray array) {...}`
<details>
<summary>英文:</summary>
Yes, if you want to be able to call `getItemList(JSONArray)` from outside of `GithubClient` without creating an object, you'll have to make it both `public` and `static`.
Basically, `public static List<Item> getItemList(JSONArray array) {...}`
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论