-2

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
  }
}
baicai
  • 45
  • 5

1 Answers1

0

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) {...}

karllindmark
  • 6,031
  • 1
  • 26
  • 41
  • If I want to call `getItemList` inside the `GitHubClient` class, do I need to create an object if the method is non-static? – baicai Jul 25 '20 at 22:37
  • 1
    Nope, you can just call it as `GithubClient.getItemList(...)` there too. Prefer the static call over just `getItemList(...)` in that case. :-) – karllindmark Jul 25 '20 at 22:43
  • 1
    A non-static method **must** be called on an instance of the object. Because that's what they're for. There are two divisions of methods, ones that belong to a particular object and ones that do not. The latter are called "static". You're asking for static behavior but on something that isn't static - it's contradictory. – user13784117 Jul 26 '20 at 01:03