#Public Classes

11 messages · Page 1 of 1 (latest)

quick reef
#
  1. Why a file cannot contain two public classes
  2. Why the file name should be the same as the public class name
little cryptBOT
#

This post has been reserved for your question.

Hey @quick reef! Please use /close or the Close Post button 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.

tepid meteor
#
  1. because of 2). A file has only one name.

  2. 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.

oblique mesa
#
  1. Java enforces the rule of having only one public class per file primarily for maintainability and clarity.
#
  1. 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.
quick reef
oblique mesa
#

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.

tepid meteor
#

Those are runtime issues, and it's not "might", it won't work period. We're talking about compiler questions

#

And, I shall add that I already answered the questions