Java初学者:如何使编译生成的Class文件名与Java文件名一致?
Hey there! I totally get this confusion when you're just starting out with Java—let's break down why this is happening and how to fix it quickly.
Why the Class Name Doesn't Match Your File Name
Java has a strict rule here: the name of a public class must exactly match the name of its .java file (and yes, this includes uppercase/lowercase letters, since Java is case-sensitive).
In your case, your file is named FirstProgram.java, but inside that file you must have a public class HelloWorldApp definition. The Java compiler uses the name of the public class to generate the .class file, which is why you're getting HelloWorldApp.class instead of FirstProgram.class.
Step-by-Step Fix
Let's get those names aligned:
- Open your
FirstProgram.javafile in Notepad (or any text editor). Look for the line that starts withpublic class—it probably looks like this:public class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World"); } } - Rename the class to match your file name. Change
HelloWorldApptoFirstProgram, so the code becomes:public class FirstProgram { public static void main(String[] args) { System.out.println("Hello World"); } } - Save the file (make sure you don't accidentally change the file extension—keep it
.java, not.txt). - Recompile the file in cmd with:
Now you'll seejavac FirstProgram.javaFirstProgram.classgenerated, which matches your Java file name perfectly!
Quick Extra Tip
If your Java file doesn't have a public class, the compiler will generate a .class file named after the first class in the file. But it's always a good practice to stick with one public class per file, and keep the class name and file name identical—it makes your code way easier to organize and debug as you learn more.
内容的提问来源于stack exchange,提问作者itsTed

