Search code examples
classsyntaxinterfacelanguage-designabstract

Why differentiate, at a syntactic level, between interface and abstract class?


(DISCLAIMER: This is NOT a question about understanding the difference between abstract classes and interfaces. If you didn't get that, please read the title again. I am well-versed in the difference between a contract and a half-implemented subsystem.)

Let's take Java as just one example. It seems that there is little need for a distinct keyword interface, when from my point of view as a developer, the compiler spits out exactly the same thing, which in human-speak is, "You cannot utilise this until you derive (via implements or extends) a new class which implements its methods". Simple.

But there is one scenario which may prevent conflation of these two: When we need to implement more than one interface, since Java does not allow multiple inheritance (for classes). Surely it would be trivial to build the language in such a way that the compiler recognises when there are any method bodies or declared variables, and subsequently disallows multi-implements/extends where appropriate? Does order of precedence then present a problem?

Is this the only reason we have this syntactic differentiation?

P.S. One reason I ask this question is that this scenario can present quite a challenge in understanding for new OO programmers, and I think that handling this in a more streamlined fashion, at the language level, would greatly assist in more quickly grasping the conceptual differences.


Solution

  • Surely it would be trivial to build the language in such a way that the compiler recognises when there are any method bodies or declared variables, and subsequently disallows multi-implements/extends where appropriate?

    Let's say you did do that. So your language lets you do this:

    class Foo extends A, B, C {
    }
    

    And it doesn't complain as long as every method in B and C is abstract. Fine and dandy.

    Now let's say that you didn't create B. It's in some other package someone else wrote. They don't know anything about your class Foo. When they made B, everything in it was abstract, but that was just a coincidence: they didn't happen to have anything concrete to put in there yet.

    Later, they decide to add another method to B, which is concrete. Now, without realizing it, they've broken your class Foo.

    One argument for having an explicit interface construct is that it makes the intent of the author of B clear to someone consuming it.

    In general, I think your question is a good one. The language I work on, Dart, is actually close to what you're talking about: It has an explicit interface syntax now, but it's being removed in favor of pure abstract classes.