#Public Classes
11 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @quick reef! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
-
because of 2). A file has only one name.
-
that was made a requirement for optimization in compiling in case of very large projects. When some .java file imports and uses a class from another package, therefore a public class, it should be immediate enough to locate the .java file that defines that class.
- Java enforces the rule of having only one public class per file primarily for maintainability and clarity.
- The requirement that the file name should be the same as the public class name is closely related to how the Java compiler and runtime locate classes. When the Java compiler compiles a source file, it looks for a public class and creates a bytecode file with the same name as the class. This convention helps the Java classloader to find and load classes efficiently.
but the compiler is still able to compile and run a class file even if it's name is not the same as the file.
Java's class loader uses the class name to find the corresponding .class file. If the file name and class name don't match, the class loader might not be able to locate and load the class.
Ensuring that the file name matches the public class name helps maintain uniqueness in the naming of classes and their corresponding files, avoiding conflicts in large projects.