与构造函数同名的方法 - 为什么? [英] Methods With Same Name as Constructor - Why?

查看:149
本文介绍了与构造函数同名的方法 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么允许以下内容:

public class Foo {
  public Foo() { ... }
  public void Foo() { ... }
}

有吗命名方法与类相同的有效理由?

Is there ever a valid reason for naming a method the same as the class?

推荐答案

我的猜测是允许的,因为明确禁止它会为Java的标识符命名规则添加另一个要求,但收效甚微。与C ++不同,Java总是要求使用 new 关键字调用构造函数,因此对于标识符是指方法还是构造函数,从不存在任何歧义。我确实同意一个与其父类同名的方法乍一看是相当混乱的,应该几乎可以避免。也就是说,我很高兴他们选择不通过禁止这种方法来进一步复杂化语言。

My guess is that it's allowed because explicitly disallowing it would add another requirement to Java's identifier naming rules for very little benefit. Unlike, say, C++, Java always requires that constructors are called with the new keyword, so there's never any ambiguity about whether an identifier refers to a method or a constructor. I do agree that a method with the same name as its parent class is quite confusing at first glance, and it should be almost certainly be avoided. That said, I'm glad they chose not to further complicate the language by banning such methods.

这篇关于与构造函数同名的方法 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆