Etichettato: programmer rant

Interfaces in Java could be useful, but they suck instead

I usually dislike interfaces in favor of abstract classes, because I often have common code to share between many classes. The abstraction level of interfaces is kind of “I don’t REALLY know what will fit in here”, and this is almost never the case in what I do.

Obviously interfaces ARE useful sometimes and DO have their uses, I know, but I often try to use them (for instance, for java generics) and then backoff using something else because they don’t do what I would expect.

As an example, today I thought of interfaces as a way to limit the access to a particolar method to classes that have no common ancestor (no multiple inheritance in Java) and are in different packages (no default access). How hard could it be? You just define an interface with a protected method

interface AccessControlInterface {
    protected void protectedMethod();

and then implement the interface and the method in any class you want, making it possible to call A.protectedMetod() from class B only if B implements AccessControlInterface. Dead simple, right?

Wrong. As it turns out, in Java the only valid modificators for methods in interfaces are public and abstract. Yeah, abstract, the most useful keyword to use in something that can’t be anything else than abstract.

Is it just me, or there should be a giant WHY in the sky right now?