Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

I have a file Test.java and the following code inside it.

public class Abcd

{

        //some code here

}

Now the class does not compile, but when I remove the public modifier , it compiles fine.

What is the reasoning behind Java allowing us to compile a class name that is different from the file name when it is not public.

I know it is a newbie question, but I'm not able to find a good explanation.

1 Answer

0 votes
by (46k points)
The rationale is to allow more than one top-level class per .java file.

Many classes—such as event listeners—are of local use only and the earliest versions of Java did not support nested classes. Without this relaxation of the "filename = class name" rule, each and every such class would have required its own file, with the unavoidable result of endless proliferation of small .java files and the scattering of tightly coupled code.

As soon as Java introduced nested classes, the importance of this rule waned significantly. Today you can go through many hundreds of Java files, never chancing upon one which takes advantage of it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...