英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论