53

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.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
lzjun
  • 701
  • 1
  • 5
  • 8

2 Answers2

107

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.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • 3
    +1 Finally a sane answer. Thank you. :) – weltraumpirat May 10 '12 at 16:13
  • 4
    I do my best. After all, we're all in this together! – Nathaniel Ford May 10 '12 at 16:15
  • 2
    @NathanielFord, are we really? I've been grossly misinformed. – jn1kk May 10 '12 at 16:24
  • If don't follow the rules in a class declaration a compile-time error occurs. – Paul Vargas May 10 '12 at 16:26
  • 1
    Goodness, I am glad to find that someone gave a concrete answer instead of rubbish like "Because that's how Java is", "...because that's the way the lexer mandates it?". -_- Only detracting from the community. – Will Oct 24 '18 at 14:06
  • I think this is also done because we can implement multiple interfaces, So it is easy to update any new interface implementation at the end which looks clean. – Akhilesh Dhar Dubey Jan 26 '21 at 02:06
  • This has changed with Kotlin – Gilbert Feb 14 '21 at 17:18
  • 1
    @Ssenyonjo I'm not entirely sure what you mean by 'this', but the class declaration for interfaces is [pretty different](https://kotlinlang.org/docs/interfaces.html#implementing-interfaces) in Kotlin. While it's also a JVM language, I'm not sure that that fact really applies to the question being asked here? – Nathaniel Ford Feb 14 '21 at 19:51
5

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

trutheality
  • 23,114
  • 6
  • 54
  • 68