为什么Java允许我们编译名称与文件名不同的类? [英] Why does Java allow us to compile a class with a name different than the file name?

查看:35
本文介绍了为什么Java允许我们编译名称与文件名不同的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 Test.java 和其中的以下代码.

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

public class Abcd
{
        //some code here

}

现在该类无法编译,但是当我删除 public 修饰符时,它可以正常编译.

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

Java背后的原因是,允许我们编译一个与文件名不公开的文件名不同的类名.

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.

推荐答案

基本原理是每个 .java 文件允许一个以上的顶级类.

The rationale is to allow more than one top-level class per .java file.

许多类(例如事件监听器)仅在本地使用,最早的Java版本不支持嵌套类.如果不放松"filename = class name"规则,则每个此类都将需要自己的文件,不可避免的结果是小型 .java 文件无休止的扩散以及紧密耦合的分散代码.

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.

Java引入嵌套类后,此规则的重要性就大大降低了.今天,您可以浏览成百上千个Java文件,而永远不会选择利用它的文件.

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.

这篇关于为什么Java允许我们编译名称与文件名不同的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆