我们可以在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 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短