私有方法调用约定
我最近才开始学习Java。我有一个更多关于Java中使用的约定的问题...
所以假设我有类A:
public class A {
public void methodA{
methodB();
}
private void methodB{
}
}
有时我看到有些人使用this调用类内部的私有方法(例如this.methodB(); )即使没有歧义。明确向人们表明他们正在调用私有方法是惯例还是这只是某人的“风格”。
I just recently started learning Java. I have a question which is more about conventions used in Java...
So suppose I have class A:
public class A {
public void methodA{
methodB();
}
private void methodB{
}
}
Sometimes I see some people calling private methods inside the class using this (e.g. this.methodB(); ) even if there is no ambiguity. Is it convention to explicitly show people that they are invoking private method or is it just someone's 'style'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就其本身而言,使用
this
并不能说明太多问题。它可以指向:this
的内部类,无论其可见性如何。this
的类继承的类之一的静态字段或方法或嵌套类。 (这种情况下通常会出现警告,但这只是警告)。它确实防止的是:
我要强调的是,它根本不保证所调用的方法是私有的。
这是我第一次听说这个规则——我怀疑,它顶多是一个公司的风格规则(没有多大帮助)。
In and of itself, using
this
does not clarify much. It can point to:this
, whatever its visibility.this
's class. (there is usually a warning in that case, but it is only a warning).What it does prevent is:
I'll emphasize that it does not guarantee at all that the method called is private.
It is the first time I hear of this rule - I suspect that, at most, it is a (not that helpful) style rule of a company.
这只是风格。就个人而言,我在某种程度上喜欢在访问成员时过于明确,但我也可以理解人们觉得它很难看,特别是如果您使用内部类中外部类的方法或属性:
在极少数情况下,您引入稍后会出现名称隐藏问题,而您却没有注意到 - 突然间您调用了错误的函数或访问了错误的变量。尽管如此,使用
this
进行限定还是很冗长,而且这不是通用规则。That's just style. Personally, I somehow like being overly explicit when accessing members, but I can also understand that people find it ugly, particularly if you're using methods or properties of the outer class from an inner class:
It may help in rare cases where you introduce a name shadowing problem later without noticing - all of a sudden you're calling the wrong function or accessing the wrong variable. Still, qualifying with
this
is verbose, and it's not a general rule.有点偏离主题,因为我们不是在处理私有方法,而是在处理私有类变量,但值得一提的是,有时
this
对于防止歧义是必要的:总的来说,在没有歧义的情况下那么
this
是多余的语法。Slightly off-topic in that we're not addressing a private method, rather a private class variable, but it's worth mentioning that sometimes
this
is necessary to prevent ambiguity:On the whole, where there is no ambiguity then
this
is redundant syntax.