Why “extends” precedes “implements” in class declaration [closed]

半城伤御伤魂 提交于 2019-11-27 09:37:13

问题


Why must implement always be written after extend in a class declaration? For example:

public class Register extends ActionSupport implements ModelDriven

Why can it not be:

public class Register implements ModelDriven extends ActionSupport 

The latter produces a compile-time error.


回答1:


When the Java compiler turns a class into bytecode, it must first look to a parent class. That is because the underlying implementation of classes is to point to the bytecode of the parent class - which holds the relevant methods and fields. Then it adds in pointers to the code of the child class functions - some of which are mandated by the 'implements' keyword.

Because the parent class must be compilable, it is easier if the compiler knows up front what that class is. Further, you can extend only one class but implement any number of interfaces. The compilation time climbs if the extends keyword can be intermingled amongst any number of implements instructions. Compilers want to fail as fast as possible to decrease dev time, so this choice is logical. Further, it helps you think clearly about the class for the same reason.




回答2:


Probably to make the compiler's job easier. It's just a convention. There isn't any advantage to being able to rearrange these things.

It's like asking why Java functions aren't written in pre-order notation like public int (int a, int b)add{ return a+b; }.



来源:https://stackoverflow.com/questions/10538010/why-extends-precedes-implements-in-class-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!