Home > Java > javaTutorial > Why Does My Java Code Show 'class X is public should be declared in a file named X.java'?

Why Does My Java Code Show 'class X is public should be declared in a file named X.java'?

DDD
Release: 2024-12-21 09:07:14
Original
258 people have browsed it

Why Does My Java Code Show

Class Name and Source File Name Mismatch

The error "class X is public should be declared in a file named X.java" indicates a discrepancy between the name of the public class and the name of the source file containing it.

The rules for Java naming conventions dictate that a public class must always be declared within a file with the same name as the class itself, with the extension ".java." For instance, a public class named "MyClass" should be declared in a file called "MyClass.java."

Solution

To resolve this issue, you can either rename your source file or rename the public class within the file. Here are the steps you can take:

  • Rename Source File: Change the name of your source file to match the name of the public class. In this case, change "Main.java" to "WeatherArray.java."
  • Rename Public Class: Change the name of the public class within the file to match the name of the source file. Adjust the code to:
public class Main {
    public static void main(String[] args) {
        // ...
    }
}
Copy after login

The above is the detailed content of Why Does My Java Code Show 'class X is public should be declared in a file named X.java'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template