我们可以在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 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短