简体   繁体   中英

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.

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. 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.

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.
  • 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. 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).

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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