Question

I am starting out in Java API design and in reading existing code bases, I have found that most APIs consist of interfaces only with their implementations bundled in a different package.

Having read that interfaces are generally more problematic to use/maintain than abstract classes, why aren't abstract classes used instead of interfaces?

Was it helpful?

Solution

What's an API ? It is an interface by definition.

Consider the software you're using as a blackbox. You're not supposed to know how things are done internally, nor are you supposed to want that, or you would just build things yourself. Besides, trying to extend an API class yourself may break the tool's behaviour (which, once again, you don't really know).

The software you are using and your own softwares are two different softwares, so the only thing you should need is the link between them, namely the interface. See what an interface means in computer science and you should understand why it applies to the OOP meaning of the word.

Now as for your abstract class argument, it seems completely subjective. As far as I'm concerned, a class in Java can implement several interfaces but extend only one base class.

OTHER TIPS

Not sure where you read that interfaces are more problematic to use or maintain. You can only inherit from one base class, but you can implement as many interfaces as you want, so interfaces are inherently more flexible. E.g. Consider what would happen if Closeable and Readable were abstract classes; you'd have no way of making, say, a FileReader that subclasses both.

The main reason is that Interfaces allow you to provide a common ground between your implementation and who ever is making use of your code. There are scenarios where you do not want the caller to know how you are executing certain pieces of logic. The reasons for this can be security or proprietary algorithms, to mention a few.

When you define an interface, you outline what functions you will be offering. In most cases, the caller will not care how you have implemented, say, a sorting mechanism. The caller simply cares that it works.

Coding to an interface also gives you a relatively large degree of freedom since you are, at no point, constraining yourself to implemented logic. So, if your method yields a List instead of an ArrayList, you are giving the freedom to the caller to resolve that to any class which implements list.

As @Benjamin Rogge said, I would also like to see where you read that abstract classes are more difficult to maintain.

Licensed under: CC-BY-SA with attribution
scroll top