You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java初学者:如何使编译生成的Class文件名与Java文件名一致?

Fixing Mismatched Java File and Class File Names

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:

  1. Open your FirstProgram.java file in Notepad (or any text editor). Look for the line that starts with public class—it probably looks like this:
    public class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }
    
  2. Rename the class to match your file name. Change HelloWorldApp to FirstProgram, so the code becomes:
    public class FirstProgram {
        public static void main(String[] args) {
            System.out.println("Hello World");
        }
    }
    
  3. Save the file (make sure you don't accidentally change the file extension—keep it .java, not .txt).
  4. Recompile the file in cmd with:
    javac FirstProgram.java
    
    Now you'll see FirstProgram.class generated, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:22:18