简体   繁体   English

Java编译器如何检查接口中的所有方法是否都已实现?

[英]How does the java compiler check if all methods in an interface were implemented?

If I declare that my object implements an interface, but fail to implement those methods, when I compile my code, I get a compiler error. 如果我声明我的对象实现了一个接口,但未能实现那些方法,那么在编译代码时,我会收到编译器错误。 How does the java compiler know that I haven't implemented all of the methods of an interface? Java编译器如何知道我尚未实现接口的所有方法?

How does the java compiler know that I haven't implemented all of the methods of an interface? Java编译器如何知道我尚未实现接口的所有方法?

It knows all methods that your class has implemented because it has found and analyzed them during the compilation. 它知道您的类已实现的所有方法,因为它已在编译期间找到并分析了它们。

It knows all of the methods that were defined in all of the superclasses and interfaces of your class because: 它知道在类的所有超类和接口中定义的所有方法,因为:

  1. it has either just compiled their source code, or loaded their ".class" files, and 它要么只是编译了其源代码,要么已加载了其“ .class”文件,并且

  2. it has analysed the interfaces / classes and figured out which methods need to be implemented by your class. 它分析了接口/类,并弄清了您的类需要实现哪些方法。

Then it compares the two sets of methods. 然后,它比较了两组方法。 (Note that the methods don't need to be exactly the same. For example, the actual method could return a subtype of the return type of the method in the interface. The set comparison needs to take account of that.) (请注意,方法不必完全相同。例如,实际方法可以在接口中返回方法返回类型的子类型。集合比较需要考虑到这一点。)


(Actually, that is just one approach to doing this check. An actual Java compiler might do the checking a bit differently.) (实际上,这只是执行此检查的一种方法。实际的Java编译器执行检查的方式可能有所不同。)

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

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