我们可以在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 生日广州男生祝福语简短