Java:外部类和内部类方法之间的名称歧义
假设我有:
public class OuterClass() {
public class InnerClass {
public void someMethod(int x) {
someMethod(x);
}
}
public void someMethod(int x) {
System.out.println(x);
}
}
如何解决外部类的 someMethod()
和内部类的 someMethod()
之间的歧义?
Suppose I have:
public class OuterClass() {
public class InnerClass {
public void someMethod(int x) {
someMethod(x);
}
}
public void someMethod(int x) {
System.out.println(x);
}
}
How do I resolve the ambiguity between the someMethod()
of the outer class and the someMethod()
of the inner class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
OuterClass.this
引用外部,或者使用OuterClass.this.method()
调用该方法。然而,从设计的角度来看,至少可以说,共享名称是令人困惑的。如果内部类代表一个扩展或者抽象方法的具体实现,这可能是合理的,但通过调用 super.method 会更清楚。直接调用超级方法(看起来像您打算这样做?)是令人困惑的。
You can refer to the outer with
OuterClass.this
, or call the method withOuterClass.this.method()
.However, as a point of design, sharing the name is confusing, to say the least. It might be reasonable if the inner class represented an extension or, say, a concrete implementation of an abstract method, but that would be clearer by calling super.method. Calling a super method directly, (as it looks like you're intending to do?), is confusing.
使用
OuterClass.this.someMethod()
将其范围限定为外部类:Scope it to the outer class with
OuterClass.this.someMethod()
:重命名歧义是一个很好的做法。特别是如果你将它应用在向上和向后的架构中。
Renaming ambiguity is a good practice. Especially if you apply it in the upward and backward architecture.