我们可以在Java中定义与类名称相同的方法名称吗?
是的,可以定义一个与类同名的方法。没有编译时或运行时错误。但是,按照Java中的编码标准,不建议这样做。通常,Java中的 构造函数名称和类名称始终相同。
示例
public class MethodNameTest {
private String str = "Welcome to nhooo";
public void MethodNameTest() { // Declared method name same as the class name
System.out.println("Both method name and class name are the same");
}
public static void main(String args[]) {
MethodNameTest test = new MethodNameTest();
System.out.println(test.str);
System.out.println(test.MethodNameTest());
}
}在上面的例子中,我们可以声明的方法名(MethodNameTest)相同类名(MethodNameTest),将没有任何错误编译成功。
输出结果
Welcome to nhooo Both method name and class name are the same
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短