在Java中,在同一类中调用非静态方法而无需创建对象

huangapple 未分类评论47阅读模式
英文:

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 = &quot;abc&quot;

  public List&lt;Item&gt; 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&lt;Item&gt; 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&#39;ll have to make it both `public` and `static`.

Basically, `public static List&lt;Item&gt; getItemList(JSONArray array) {...}`

</details>



huangapple
  • 本文由 发表于 2020年7月26日 06:30:29
  • 转载请务必保留本文链接:https://java.coder-hub.com/63094207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定