简体   繁体   English

为什么类编译为.class但接口不编译为.interface

[英]Why classes compile to .class but interface does not to .interface

是否有任何具体原因导致接口未编译成编译成.interface文件的MyInterface.java?但是任何类都被编译成.class文件。

因为要点是指示文件是Java字节代码 (而.class是为其选择的扩展名),而不是特定的语言结构。

The physical representation of the byte-code on the file system doesn't matter. 文件系统上字节代码的物理表示无关紧要。

It's the logical realization (whether class or interface) that matters. 重要的是逻辑实现(无论是类还是接口)。

Java treats interfaces almost like classes, eg they share the same namespace (you can't have an interface that has the same name as a class) and a compiled interface is almost identical to a compiled abstract class. Java将接口视为类似于类,例如它们共享相同的命名空间(您不能拥有与类同名的接口),并且编译的接口几乎与编译的抽象类相同。

So it would not make any sense to store them in a different format or with a different file extension. 因此,将它们以不同的格式存储或使用不同的文件扩展名是没有任何意义的。 On the contrary, this would make many things harder. 相反,这会使许多事情变得更难。 For example, when you load a class or interface by name (Class.forName("my.class.name")) Java does not know whether it is a class or an interface. 例如,当您按名称加载类或接口(Class.forName(“my.class.name”))时,Java不知道它是类还是接口。 If there would be two different extensions, Java would have try to find a file "my/class/name.class" and then "my/class/name.interface", instead of only trying the first one. 如果有两个不同的扩展,Java会尝试找到一个文件“my / class / name.class”,然后是“my / class / name.interface”,而不是只尝试第一个。

That's the way the language designers decided. 这就是语言设计师决定的方式。

It makes sense in several ways: 它在几个方面有意义:

  • .class files are a byproduct that you don't normally see or manipulate by hand. .class文件是您通常不会手动查看或操作的副产品。
  • The less different extensions a program uses, the easier it is to maintain. 程序使用的扩展程度越小,维护起来就越容易。
  • In many cases, there's no distinction in the code between a class and an interface, so it's logical that the binary files look alike. 在许多情况下,类和接口之间的代码没有区别,因此二进制文件看起来很相似是合乎逻辑的。

Frankly, I can't think of a good reason to have different extensions for compiled classes and interfaces. 坦率地说,我想不出有一个很好的理由对编译的类和接口有不同的扩展。 Why would it be important to distinguish between them? 为什么区分它们很重要?

In java, you have source files, called .java and binaries called .class. 在java中,您有源文件,称为.java和名为.class的二进制文件。 Its just a choice of naming. 它只是一个命名选择。

Also for java classes and interface's don't differ that much (a class just contains a lot of extra information like method bodies). 同样对于java类和接口来说,差别不大(类只包含很多额外的信息,比如方法体)。

It is just a choice they made. 这只是他们的选择。 I wouldn't bother about it. 我不打扰它。 It is a binary file anyway. 无论如何,它是一个二进制文件。 One way to think is "Even it is an interface it is still in a file.java". 一种思考方式是“即使它是一个仍然在file.java中的接口”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM