What if no class is public?

QuestionsQuestions8 SkillsProYour First Java LabNov, 29 2025
059

If no class in a Java file is declared as public, then the following applies:

  1. File Naming: The file name does not need to match any class name. You can name the file anything you like, as long as it has a .java extension.

  2. Access Control: All classes in the file will have package-private access by default. This means they can only be accessed by other classes in the same package.

  3. Compilation and Execution: You can compile and run the program as usual, but you won't be able to run it directly from the command line unless you specify a class with a main() method. If there are multiple classes, you need to ensure that one of them contains the main() method to serve as the entry point.

Example:

// File: MyClasses.java
class FirstClass {
    void display() {
        System.out.println("This is the First Class.");
    }
}

class SecondClass {
    void show() {
        System.out.println("This is the Second Class.");
    }
}

class MainClass {
    public static void main(String[] args) {
        FirstClass first = new FirstClass();
        first.display();
        
        SecondClass second = new SecondClass();
        second.show();
    }
}

In this example:

  • The file is named MyClasses.java.
  • None of the classes are public, so the file name does not need to match any class name.
  • The MainClass contains the main() method, which serves as the entry point.

If you have further questions or need clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!