Two Most Important Questions asked in Java Interviews

Abhinay Gupta
3 min readJun 9, 2023

These two questions have been asked a lot of times to me in interviews:

  1. Why there is only single public class per source file?

2. Why non static method cannot be called from a static method?

1. Why there is only single public class per source file?

In Java, there can only be one public class per source file, and it must have the same name as the source file. This restriction is enforced by the Java language specification and is designed to ensure consistency and clarity in code organization. Here are a few reasons why this restriction exists:

1. Accessibility and Visibility: The access modifiers (`public`, `private`, etc.) control the visibility of classes, methods, and fields. When a class is declared as `public`, it means it can be accessed from other classes and packages. Having multiple `public` classes in a single file would create ambiguity in terms of which class is intended to be accessed publicly.

2. Compilation and Naming Conventions: Java source files follow a convention where the file name matches the name of the public class defined within it. This convention simplifies the compilation process and helps the compiler locate the appropriate class definition. If there were multiple public classes in a single file, it would be unclear which class should match the file name.

--

--

Abhinay Gupta

Exploring personal growth, tech, and culture through engaging storytelling | Inspiring and connecting with readers worldwide.