Why only one .class file is created in java & which is declared first?

95 Views Asked by At

In Java:

class A{}
class a{}

after compilation : A.class

class a{}
class A{}

after compilation : a.class

Why only one class created? the first we declared only that .class file generated

Please explain the reason in detail.

1

There are 1 best solutions below

11
Tom Elias On

Historically in Java, the name (and case) of the "main" public class of the file had to match the file name. So public class A has to be in the file A.java and will compile into A.class and you will run it's main() method using "java A". we have to name the class and the file the same way.

The second class in the file is not public (implicitly protected since no modifier was given) and is not nested under the A class. no one outside the package of class A will be able to use it. therefore it does not need its' own class file.

That is Java's way of implementing the principle of "Encapsulation". you could create classes and sub-classes in your code, and anyone who receives the compiled products of these classes will not be able to see the internal structure of your code.