如何在另一个类中访问私有方法?

huangapple go评论64阅读模式
英文:

How to access private method in another class?

问题

不能在另一个类中为私有方法创建getter/setter。如果不改变方法的访问权限(除非那是唯一的方法),我该如何访问这个方法呢?例如,这是一个类:

public class PlanBook {
    private boolean isPlanGoing(int plan) {
        //......
    }
}

在另一个需要使用这个方法的类中,我正在这样做:

PlanBook pb = new PlanBook();
pb.isPlanGoing(1234);

但是Intellij 告诉我我不能这么做,因为"____ 在 ______ 中具有私有访问权限"。

英文:

Can you do a getter/setter for a private method in another class? If not, how would I access this method (without changing it from private to public unless that's the only way). For example, this is one class:

public class PlanBook {
      private boolean isPlanGoing (int plan){
      .....
      }
}

In another class where I have to use this method, I'm doing:

PlanBook pb = new PlanBook();
pb.isPlanGoing(1234);

But Intellij is telling me I can't do it cause its private "____ has private access in ______"

答案1

得分: 1

你最好的选择可能是创建一个调用你的私有方法的公共方法。

public class PlanBook {
    private boolean isPlanGoing(int plan) {
      ...
    }
    public boolean isThisPlanGoing(int plan) {
      return isPlanGoing(plan);
    }
}
英文:

Your best option is likely to create a public method that calls your private method.

public class PlanBook {
    private boolean isPlanGoing(int plan) {
      ...
    }
    public boolean isThisPlanGoing(int plan) {
      return isPlanGoing(plan);
    }
}

答案2

得分: 0

如果该方法是私有的,则无法从另一个类访问它。
通常针对需要从其他类访问的私有属性,您会使用 "getter" 和 "setter"。

例如,将以下内容添加到 PlanBook 类中:

public boolean getIsPlanGoing(int plan) {
      return isPlanGoing(plan);
}
英文:

If the method is private you cannot access it from another class.
Usually for private attributes that need to be access from other classes you use "get-ers" and "set-ers".

For example, adding this to the PlanBook class:

public boolean getIsPlanGoing(int plan) {

      return isPlanGoing(plan);

} 

huangapple
  • 本文由 发表于 2020年10月14日 02:16:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64340888.html
匿名

发表评论

匿名网友

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

确定