为什么Java中的文件名与公共类名相同?

时间:2021-12-30 15:37:48

In Java, the name of the file should be the same as the name of the public class contained in that file. Why is this a limitation? What purpose does it serve?

在Java中,文件的名称应该与该文件中包含的公共类的名称相同。为什么这是一个限制?它的作用是什么?

9 个解决方案

#1


42  

Java had an interesting approach--where giving a programmer a choice can only degrade the programming experience, remove the choice.

Java有一种有趣的方法——给程序员一个选择只能降低编程体验,取消选择。

They did this in quite a few places. Filenames and packages for sure, but also not allowing multiple public classes in a file (never good), not allowing you to split classes between files (Damn hard to work with!), etc.

他们在很多地方都这样做过。可以肯定的是文件名和包,但也不允许在文件中有多个公共类(从来都不好),不允许在文件之间分割类(非常难处理!)等等。

I really wish they had gone a few further. There is no reason for public variables--I've never needed one, nor have I ever seen a situation where some smart programmer thought one was needed and was actually right.

我真希望他们能更进一步。公共变量是没有理由的——我从来都不需要它,也从来没有见过有哪个聪明的程序员认为它是需要的,而且实际上是对的。

I also wouldn't mind seeing method/class size limitations, but this could get sketchy (it could easily be implemented by code checkers, the problem is typically that the companies that need the most help are the ones that don't know they need help and, therefore, don't use tools like code checkers).

我也不介意看到方法/类大小的限制,但是这可能会变得粗糙(它很容易被代码检查器实现,问题是最需要帮助的公司通常是那些不知道需要帮助的公司,因此不使用代码检查器之类的工具)。

This isn't stuff that matters to most small teams, but when your team grows and has multiple sites with consultants from India, China, and various other spots throughout the world, You'll start to appreciate the inflexibility.

对大多数小团队来说,这不是什么重要的东西,但是当您的团队成长起来,并且拥有来自印度、中国和世界各地的咨询顾问的多个站点时,您将开始认识到这种不灵活性。

In response to setters/getters comment:

就setters/getters的评论:

Java beans were an abomination created by Borland to hack their GUI up, then retrofitted into Java.

Java bean是Borland创建的一种令人厌恶的东西,它被用来破坏GUI,然后被改造成Java。

Horrid idea--a distraction from OO programming--Getters and setters A) show too much of your implementation and B) make you think in terms of operating on data from another object rather than asking the other object to execute an operation for you. Bad hack for people who can't yet think in OO.

可怕的想法——从OO编程中分心——getter和setter a)显示了太多的实现,B)让您考虑如何操作来自另一个对象的数据,而不是让另一个对象为您执行操作。对那些还不会用OO思考的人来说,这是一个糟糕的黑客。

Getters are needed occasionally but shouldn't be added unless seen to be absolutely unavoidable.

偶尔也需要getter,但除非被认为是绝对不可避免的,否则不应该增加。

Setters should be avoided at all costs. If you absolutely need to externally modify the state after an object is constructed, try to use the builder pattern and protect your setters from being called after any operation has been executed.

应该不惜一切代价避免定居者。如果您绝对需要在构建对象之后从外部修改状态,请尝试使用builder模式,并在执行任何操作之后保护您的setter不被调用。

There are obviously exceptions to everything, and many "Getters" are actually critical object business logic, like String.length() which would be required no matter how String was implemented and isn't even implemented by just returning a property--a great case for a "Getter" if you even want to call it that.

显然,所有的事情都有例外,而且许多“Getter”实际上是关键的对象业务逻辑,比如String.length(),无论字符串是如何实现的,甚至不是通过返回一个属性来实现的——这对于“Getter”来说是一个很好的例子,如果你想这样称呼它的话。

#2


15  

I was about to say, that it is simply a must. But I looked at the JLS, and it is not that strict. From the JLS's perspective, it is left to the compiler to choose whether to set such a restriction or not.

我正要说,这是必须的。但是我看了JLS,它并没有那么严格。从JLS的角度来看,编译器可以选择是否设置这样的限制。

Practically spoken - common compilers do have that restriction, and, as other already explained, it's much easier for the compiler to find a compilation unit or for a classloader to find a class file with such a restriction in place.

实际上,一般的编译器都有这个限制,而且,正如其他已经解释过的那样,编译器更容易找到一个编译单元,或者类加载器更容易找到一个有这个限制的类文件。

#3


11  

TO be more specific the filename shoud have same name as the public class name in that file. which is the way to tell the JVM that this is what the entry point is for you.

更具体地说,文件名应该与该文件中的公共类名具有相同的名称。这是告诉JVM这是您的入口点的方法。

#4


6  

It is just the convention set by Sun, the makers of Java.
The purpose is organization; the reason is so that everyone who codes in Java will have a consistant way of naming files.

这只是Sun公司的惯例,Java的制造者。目的是组织;原因是这样的,用Java编写代码的每个人都有一种一致的命名文件的方式。

#5


2  

Each public class must be in a file where the FileName matches the ClassName and a package where the Packagename represents the Directory structure, written in the dotted-form (slashes become dots, like com/example/app becomes com.example.app).

每个公共类必须位于文件名与类名匹配的文件中,以及Packagename表示目录结构的包中,这些包以点式的形式编写(斜线变成点,比如com/example/app变成com.example.app)。

This convention is not random. The compiler has to be able to find the source files and the class loader has to be able to find the implementation. Matching package names and classnames makes this really simple and, more important, fast.

这个公约不是随机的。编译器必须能够找到源文件,类装入器必须能够找到实现。匹配包名和类名使这个过程非常简单,更重要的是,非常快速。

This convention does not apply to non-public classes. This is because non-public classes have a very limited visibility and can only be used within the package where they are defined. Thus, in both cases, the compiler and the runtime environment have already located the correct files.

本公约不适用于非公开课。这是因为非公共类的可见性非常有限,只能在定义它们的包中使用。因此,在这两种情况下,编译器和运行时环境都已经找到了正确的文件。

#6


2  

Q. 'Then how does it work in the case of C++ where there is no such restriction?'

Q。“那么,在没有这种限制的情况下,它是如何工作的呢?”

A. It doesn't work. You must have a makefile. You don't need one in Java.

答:它不工作。您必须有一个makefile。在Java中不需要。

#7


1  

It is useful in locating the class. i.e. Suppose different file names are allowed and if you have created an instance of a class then the compiler has to search the class in all file instead if the file-names are same as that of the class the performance of locating and using the class is increased. Their might be other reasons too.

它在定位类时很有用。例如,假设允许使用不同的文件名,如果您创建了一个类的实例,那么编译器必须在所有文件中搜索类,而不是在文件名称与类名称相同的情况下,查找和使用该类的性能就会提高。它们也可能是其他原因。

#8


-1  

As long as it is not public a class can have a name different from its file name. The class can also have main method. Class file will be generated with the class name but not with the source file name. The class name should be used to execute it.

只要不是公共类,类就可以有与其文件名不同的名称。类也可以有主方法。类文件将使用类名而不是源文件名生成。应该使用类名执行它。

Reason is: default class is package private, thus javac doesn't have to find this source file of this to compiler some other java program from outside of package.

原因是:默认类是包私有的,因此javac不需要从包外部找到这个源文件来编译其他的java程序。

#9


-3  

good evening sir, Q)Why public classname should be java file name? ans:

晚上好先生,问)为什么公共类名应该是java文件名?答:

->to open a file or read a file Operating system or any program needs the filename. ->developer is using the java language. developer is giving instruction to the compilor to create .class file so that it can be executed later. ->to create a .class file, java compilor has to open and read the java file. for this reason develope gives instruction in two ways 1) directly the file name. 2) indirectly from other program ------------------------------------- 1st way) (1) directly the file name. ------------------------------------- developer creates a file PrivateData.java and inside this file creates a class PublicData PrivateData.java ---------------- class PublicData{ private int x=10; int getX(){ return x; } public static void main(String args[]){ System.out.println("PublicData executed"); } } --------- compile ---------- javac PrivateData.java

->打开文件或读取文件操作系统或任何程序需要文件名。->开发人员正在使用java语言。developer向编译器发出指令来创建.class文件,以便以后可以执行。->要创建.class文件,java编译器必须打开并读取java文件。出于这个原因,develope以两种方式给出指令1)直接文件名。2)间接从其他程序- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1)(1)直接文件名。- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PrivateData开发人员创建一个文件。在这个文件中创建一个类PublicData PrivateData。java - - - - - - - - - - - - - - - - -类PublicData {私人int x = 10;int getX(){返回x;} public static void main(String args[]){System.out。println(“PublicData执行”);} } - - - - - - - - - - - - - - - - - - - - - - - javac PrivateData.java编译

    DEVELOPER'S THOUGHT:
    now developer gives instruction to compilor to
    open and read PrivateData.java file and then create .class file
    for all the    classes those are inside this file.


    COMPILOR BEHAVIOUR:
    in the above compilor behaviour is to read all the class declaration those
    are inside the PrivateData.java file and convert all those into .class file
    so,

    OUTPUT:
    PublicData.class
    file is created by compilor.

-------------------------------------------
2nd way) (2) indirectly from other program
-------------------------------------------
    let developer developed below tow java files
        (1)PrivateData.java
        (2)UsePrivateData.java

        PrivateData.java
        ----------------
        class PublicData{
            private int x=10;
            int getX(){
                return x;
            }
            public static void main(String args[]){
                System.out.println("PublicData executed");
            }
        }

        UsePrivateData.java
        -------------------
        class UsePrivateData{
            public static void main(String args[]){
                PrivateData pd=new PrivateData();
                System.out.println(pd.getX());
            }   
        }

        ---------
        compile
        ----------
        javac UsePrivateData.java

        DEVELOPER'S THOUGHT:
        now developer gives instruction to compilor to
        open and read UsePrivateData.java file and then create .class file
        for all the    classes those are inside this file
        and
        indirectly gives instruction from one of the class/program, like in the
        above program is
        PrivateData pd=new PrivateData();
        here developer give indirect instruction to compilor to create
        .class file by reading PrivateData.java
        (direct instruction is "javac PrivateData.java")


        COMPILOR BEHAVIOUR:
        ->in the above compilor behaviour is to read all the class declaration those
        are inside the UsePrivateData.java file and convert all those into .class file
        provided one of the classname is equal to the filename.

        ->now compilor got one more instruction from the program(indirectly from developer)
        instruction is            
        PrivateData pd=new PrivateData();
        now compilor behaviour is different.
            i) opens the file PrivateData.java
            ii)searches for the class PrivateData in the file PrivateData.java
                if found,
                    create .class file for this class                        
                    and
                    then read all other classes and
                    create .class file for those.
                if not found
                    donot create .class file for other classes
                    inside the file
                    and
                    raise compilation error like below
                    -------------------------
                    UsePrivateData.java:3: error: cannot access PrivateData
                                    PrivateData pd=new PrivateData();
                                    ^
                      bad source file: .\PrivateData.java
                        file does not contain class PrivateData
                        Please remove or make sure it appears in the correct
                        subdirectory of the sourcepath.
                    1 error
                    ----------------------
        OUTPUT:
          depends on the above explanation.

WHAT I OBSERVED
------------------------------
->for the indirect instruction
compilor behaviour is to 1st search inside the file for
any classname to be same as the filename.

->at a time computer/os/processor/compilor can execute one
instruction.
let    one instruction is to open file and search the class
whose name is equal to the filename
to match this condition probably Sun Micorsystem/Oracle
made a rule that only one public class can be declared
inside file whose name should be equal to filename.
    (or)
also , as compilor generates error if classname is not equal
to the fileaname, so Sun Microsystem/Oracle made a rule
for the good sake of developer that public classname should
be equal to the classname and only one public class can reside
inside a java file.

MY ANSWER IS CORRECT OR NOT I DO NOT KNOW I JUST ATTEMPETED TO GIVE CORRECT ANSWER sir.

我的答案是正确的,或者我不知道我只是想要给出正确的答案,先生。

#1


42  

Java had an interesting approach--where giving a programmer a choice can only degrade the programming experience, remove the choice.

Java有一种有趣的方法——给程序员一个选择只能降低编程体验,取消选择。

They did this in quite a few places. Filenames and packages for sure, but also not allowing multiple public classes in a file (never good), not allowing you to split classes between files (Damn hard to work with!), etc.

他们在很多地方都这样做过。可以肯定的是文件名和包,但也不允许在文件中有多个公共类(从来都不好),不允许在文件之间分割类(非常难处理!)等等。

I really wish they had gone a few further. There is no reason for public variables--I've never needed one, nor have I ever seen a situation where some smart programmer thought one was needed and was actually right.

我真希望他们能更进一步。公共变量是没有理由的——我从来都不需要它,也从来没有见过有哪个聪明的程序员认为它是需要的,而且实际上是对的。

I also wouldn't mind seeing method/class size limitations, but this could get sketchy (it could easily be implemented by code checkers, the problem is typically that the companies that need the most help are the ones that don't know they need help and, therefore, don't use tools like code checkers).

我也不介意看到方法/类大小的限制,但是这可能会变得粗糙(它很容易被代码检查器实现,问题是最需要帮助的公司通常是那些不知道需要帮助的公司,因此不使用代码检查器之类的工具)。

This isn't stuff that matters to most small teams, but when your team grows and has multiple sites with consultants from India, China, and various other spots throughout the world, You'll start to appreciate the inflexibility.

对大多数小团队来说,这不是什么重要的东西,但是当您的团队成长起来,并且拥有来自印度、中国和世界各地的咨询顾问的多个站点时,您将开始认识到这种不灵活性。

In response to setters/getters comment:

就setters/getters的评论:

Java beans were an abomination created by Borland to hack their GUI up, then retrofitted into Java.

Java bean是Borland创建的一种令人厌恶的东西,它被用来破坏GUI,然后被改造成Java。

Horrid idea--a distraction from OO programming--Getters and setters A) show too much of your implementation and B) make you think in terms of operating on data from another object rather than asking the other object to execute an operation for you. Bad hack for people who can't yet think in OO.

可怕的想法——从OO编程中分心——getter和setter a)显示了太多的实现,B)让您考虑如何操作来自另一个对象的数据,而不是让另一个对象为您执行操作。对那些还不会用OO思考的人来说,这是一个糟糕的黑客。

Getters are needed occasionally but shouldn't be added unless seen to be absolutely unavoidable.

偶尔也需要getter,但除非被认为是绝对不可避免的,否则不应该增加。

Setters should be avoided at all costs. If you absolutely need to externally modify the state after an object is constructed, try to use the builder pattern and protect your setters from being called after any operation has been executed.

应该不惜一切代价避免定居者。如果您绝对需要在构建对象之后从外部修改状态,请尝试使用builder模式,并在执行任何操作之后保护您的setter不被调用。

There are obviously exceptions to everything, and many "Getters" are actually critical object business logic, like String.length() which would be required no matter how String was implemented and isn't even implemented by just returning a property--a great case for a "Getter" if you even want to call it that.

显然,所有的事情都有例外,而且许多“Getter”实际上是关键的对象业务逻辑,比如String.length(),无论字符串是如何实现的,甚至不是通过返回一个属性来实现的——这对于“Getter”来说是一个很好的例子,如果你想这样称呼它的话。

#2


15  

I was about to say, that it is simply a must. But I looked at the JLS, and it is not that strict. From the JLS's perspective, it is left to the compiler to choose whether to set such a restriction or not.

我正要说,这是必须的。但是我看了JLS,它并没有那么严格。从JLS的角度来看,编译器可以选择是否设置这样的限制。

Practically spoken - common compilers do have that restriction, and, as other already explained, it's much easier for the compiler to find a compilation unit or for a classloader to find a class file with such a restriction in place.

实际上,一般的编译器都有这个限制,而且,正如其他已经解释过的那样,编译器更容易找到一个编译单元,或者类加载器更容易找到一个有这个限制的类文件。

#3


11  

TO be more specific the filename shoud have same name as the public class name in that file. which is the way to tell the JVM that this is what the entry point is for you.

更具体地说,文件名应该与该文件中的公共类名具有相同的名称。这是告诉JVM这是您的入口点的方法。

#4


6  

It is just the convention set by Sun, the makers of Java.
The purpose is organization; the reason is so that everyone who codes in Java will have a consistant way of naming files.

这只是Sun公司的惯例,Java的制造者。目的是组织;原因是这样的,用Java编写代码的每个人都有一种一致的命名文件的方式。

#5


2  

Each public class must be in a file where the FileName matches the ClassName and a package where the Packagename represents the Directory structure, written in the dotted-form (slashes become dots, like com/example/app becomes com.example.app).

每个公共类必须位于文件名与类名匹配的文件中,以及Packagename表示目录结构的包中,这些包以点式的形式编写(斜线变成点,比如com/example/app变成com.example.app)。

This convention is not random. The compiler has to be able to find the source files and the class loader has to be able to find the implementation. Matching package names and classnames makes this really simple and, more important, fast.

这个公约不是随机的。编译器必须能够找到源文件,类装入器必须能够找到实现。匹配包名和类名使这个过程非常简单,更重要的是,非常快速。

This convention does not apply to non-public classes. This is because non-public classes have a very limited visibility and can only be used within the package where they are defined. Thus, in both cases, the compiler and the runtime environment have already located the correct files.

本公约不适用于非公开课。这是因为非公共类的可见性非常有限,只能在定义它们的包中使用。因此,在这两种情况下,编译器和运行时环境都已经找到了正确的文件。

#6


2  

Q. 'Then how does it work in the case of C++ where there is no such restriction?'

Q。“那么,在没有这种限制的情况下,它是如何工作的呢?”

A. It doesn't work. You must have a makefile. You don't need one in Java.

答:它不工作。您必须有一个makefile。在Java中不需要。

#7


1  

It is useful in locating the class. i.e. Suppose different file names are allowed and if you have created an instance of a class then the compiler has to search the class in all file instead if the file-names are same as that of the class the performance of locating and using the class is increased. Their might be other reasons too.

它在定位类时很有用。例如,假设允许使用不同的文件名,如果您创建了一个类的实例,那么编译器必须在所有文件中搜索类,而不是在文件名称与类名称相同的情况下,查找和使用该类的性能就会提高。它们也可能是其他原因。

#8


-1  

As long as it is not public a class can have a name different from its file name. The class can also have main method. Class file will be generated with the class name but not with the source file name. The class name should be used to execute it.

只要不是公共类,类就可以有与其文件名不同的名称。类也可以有主方法。类文件将使用类名而不是源文件名生成。应该使用类名执行它。

Reason is: default class is package private, thus javac doesn't have to find this source file of this to compiler some other java program from outside of package.

原因是:默认类是包私有的,因此javac不需要从包外部找到这个源文件来编译其他的java程序。

#9


-3  

good evening sir, Q)Why public classname should be java file name? ans:

晚上好先生,问)为什么公共类名应该是java文件名?答:

->to open a file or read a file Operating system or any program needs the filename. ->developer is using the java language. developer is giving instruction to the compilor to create .class file so that it can be executed later. ->to create a .class file, java compilor has to open and read the java file. for this reason develope gives instruction in two ways 1) directly the file name. 2) indirectly from other program ------------------------------------- 1st way) (1) directly the file name. ------------------------------------- developer creates a file PrivateData.java and inside this file creates a class PublicData PrivateData.java ---------------- class PublicData{ private int x=10; int getX(){ return x; } public static void main(String args[]){ System.out.println("PublicData executed"); } } --------- compile ---------- javac PrivateData.java

->打开文件或读取文件操作系统或任何程序需要文件名。->开发人员正在使用java语言。developer向编译器发出指令来创建.class文件,以便以后可以执行。->要创建.class文件,java编译器必须打开并读取java文件。出于这个原因,develope以两种方式给出指令1)直接文件名。2)间接从其他程序- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1)(1)直接文件名。- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PrivateData开发人员创建一个文件。在这个文件中创建一个类PublicData PrivateData。java - - - - - - - - - - - - - - - - -类PublicData {私人int x = 10;int getX(){返回x;} public static void main(String args[]){System.out。println(“PublicData执行”);} } - - - - - - - - - - - - - - - - - - - - - - - javac PrivateData.java编译

    DEVELOPER'S THOUGHT:
    now developer gives instruction to compilor to
    open and read PrivateData.java file and then create .class file
    for all the    classes those are inside this file.


    COMPILOR BEHAVIOUR:
    in the above compilor behaviour is to read all the class declaration those
    are inside the PrivateData.java file and convert all those into .class file
    so,

    OUTPUT:
    PublicData.class
    file is created by compilor.

-------------------------------------------
2nd way) (2) indirectly from other program
-------------------------------------------
    let developer developed below tow java files
        (1)PrivateData.java
        (2)UsePrivateData.java

        PrivateData.java
        ----------------
        class PublicData{
            private int x=10;
            int getX(){
                return x;
            }
            public static void main(String args[]){
                System.out.println("PublicData executed");
            }
        }

        UsePrivateData.java
        -------------------
        class UsePrivateData{
            public static void main(String args[]){
                PrivateData pd=new PrivateData();
                System.out.println(pd.getX());
            }   
        }

        ---------
        compile
        ----------
        javac UsePrivateData.java

        DEVELOPER'S THOUGHT:
        now developer gives instruction to compilor to
        open and read UsePrivateData.java file and then create .class file
        for all the    classes those are inside this file
        and
        indirectly gives instruction from one of the class/program, like in the
        above program is
        PrivateData pd=new PrivateData();
        here developer give indirect instruction to compilor to create
        .class file by reading PrivateData.java
        (direct instruction is "javac PrivateData.java")


        COMPILOR BEHAVIOUR:
        ->in the above compilor behaviour is to read all the class declaration those
        are inside the UsePrivateData.java file and convert all those into .class file
        provided one of the classname is equal to the filename.

        ->now compilor got one more instruction from the program(indirectly from developer)
        instruction is            
        PrivateData pd=new PrivateData();
        now compilor behaviour is different.
            i) opens the file PrivateData.java
            ii)searches for the class PrivateData in the file PrivateData.java
                if found,
                    create .class file for this class                        
                    and
                    then read all other classes and
                    create .class file for those.
                if not found
                    donot create .class file for other classes
                    inside the file
                    and
                    raise compilation error like below
                    -------------------------
                    UsePrivateData.java:3: error: cannot access PrivateData
                                    PrivateData pd=new PrivateData();
                                    ^
                      bad source file: .\PrivateData.java
                        file does not contain class PrivateData
                        Please remove or make sure it appears in the correct
                        subdirectory of the sourcepath.
                    1 error
                    ----------------------
        OUTPUT:
          depends on the above explanation.

WHAT I OBSERVED
------------------------------
->for the indirect instruction
compilor behaviour is to 1st search inside the file for
any classname to be same as the filename.

->at a time computer/os/processor/compilor can execute one
instruction.
let    one instruction is to open file and search the class
whose name is equal to the filename
to match this condition probably Sun Micorsystem/Oracle
made a rule that only one public class can be declared
inside file whose name should be equal to filename.
    (or)
also , as compilor generates error if classname is not equal
to the fileaname, so Sun Microsystem/Oracle made a rule
for the good sake of developer that public classname should
be equal to the classname and only one public class can reside
inside a java file.

MY ANSWER IS CORRECT OR NOT I DO NOT KNOW I JUST ATTEMPETED TO GIVE CORRECT ANSWER sir.

我的答案是正确的,或者我不知道我只是想要给出正确的答案,先生。