No, File Name and Class Name do NOT need to be same in Java. Here’s How.

The very first thing I was told in my java class was that the names of the .java file and the Class in java need to be same. But soon I learned it is actually a good practice to do so, but not mandatory at all.
Let us create a simple Hello world Java program.

class Main{
    public static void main(String[] args){
        System.out.println("Hello World");
        }
}

Enter fullscreen mode Exit fullscreen mode

Save the file as “Hello.java” (Class name is Main).
Now, open your terminal and give command to compile as you would normally:
javac Hello.java
and then when you want to execute, instead of typing:
java Hello
we need to type:
java Main
As you would see, our program got executed easily.

EDIT – As mentioned by @wldomiciano, if you declare the class as public, then it is mandatory to name both the class and file name exactly same.

Conclusion

At the time of execution, we just need to mention class name. Therefore, it is always advised to name the file and class alike, to not create any confusion. But as you saw, it is not a mandatory thing.

原文链接:No, File Name and Class Name do NOT need to be same in Java. Here’s How.

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容