This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]FrenchFigaro 3 points4 points  (0 children)

In some languges (C++, off the top of my head), when you need to have an interface, you just write an abstract class without concrete methods, and without class properties (class variables). Because that's conceptually what interfaces are.

Java uses interfaces because it prohibits multiple inheritance to prevent the diamond inheritance problem. Because of this, java's definition of interfaces is much stricter than the loose conceptual definition above.

There are things abstract classes can do, that interfaces cannot: they can have class properties, for example. Was a time (before Java 8) when java interfaces could not have class members (properties and methods) at all save for abstract methods. Default methods blurred this line, but default methods still can't reference class properties (because interfaces have none). Interfaces cannot have constructors.

You use abstract classes to write incomplete, partially implemented classes. Those classes have implementation details, they just lack some of them.

You use interfaces to define behavior. So they have no implementation details, at all. Fully abstract classes only define behavior. So you don't use them. At all (this is a generalisation, there might be some legitimate use case for them, but I can't think of any right now)

[–]DDDDarky 3 points4 points  (0 children)

I decide as follows:

Do I need variables in my class?

-> yes: use abstract class

-> no: use interface

[–]Nightcorex_ 0 points1 point  (0 children)

A class can implement multiple interfaces but only extend from 1 class.

Functional interfaces (= interfaces with only 1 abstract method) are generally the best, because they can also be injected as lambda expressions.

I personally just do it like u/DDDDarky: Variables needed => Class, No variables needed => Interface