Why does Java allow us to compile a class with a name different than the file name?

前端 未结 8 1734
梦毁少年i
梦毁少年i 2020-12-22 19:20

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

public class Abcd
{
        //some code here

}

Now the class does n

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 20:02

    I think allowing them is a prerequisite for nested classes. Anonymous Classes in particular dramatically reduce the number of .java files required. Without support for this, you would need lots of single method interface implementations in their own separate files from the main class they are used in. (I'm thinking of action listeners in particular)

    There is a good explanation of all nested classes in the Nested Classes Java tutorial on Oracle's website, which has examples of each. It also has a reason they are useful, which I'll quote:

    Why Use Nested Classes?

    Compelling reasons for using nested classes include the following:

    • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

    • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

    • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

    (emphasis mine)

    I am not familiar with Java spec back in the early days, but a quick search shows inner classes were added in Java 1.1.

提交回复
热议问题