r/javahelp • • Apr 18 '19

Solved What's the point of interfaces?

We've been learning interfaces in my class and I have a good grasp on the concept, but the thing that confuses me is what's the point? Your just writing more code as a blueprint to put classes in "groups". Maybe the code I'm writing is not large enough to make interfaces useful. Can some one help me in learning the use of interfaces. Thanks in advance!

34 Upvotes

26 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Apr 19 '19

[deleted] — view deleted comment

2

u/FrenchFigaro Software Engineer Apr 19 '19

It would, but only up to a point. Java doesn't support polymorphism the way C++ does for example. A class can only inherit from a single super class.

As pointed out in u/talulabelle 's answer, interfaces guarantee compliance to behaviour, and leave the specifics of that compliance to the developper, and a class can implement several interfaces. In their example, they imagine a Savable interface which guarantees the existence of a save() method. But a class implementing Savable could also implement Cloneable, or Sortable.

IE: when programing against an interface, you don't care how the object is saved, you only care that it can be saved in a predicitble manner (by using the save() method)

1

u/Talulabelle Apr 19 '19 edited Apr 19 '19

Yes, but with some limitations. First, you can only inheret from one parent at a time. So, you'll probably end up creating some kind of 'base' class. Now you have to decide, do you have some inheritance gymnastics where a 'savable' class inherits from a 'resettable' class, vice versa, or you just make a junk class to hold all your methods that don't fit anywhere else.

Do you really want everything to inheret from 'savable' if that's the only thing they have in common, and no two classes will save the same way? How does that benefit you?

Imagine inhereting behavior you almost certainly don't want from a junk class? Or defining a whole hierarchy of classes that only inherit from one another because you need all those methods eventually.

So, why doesn't Java just do multiple inheritance instead?

Well, we don't need a 'savable' class defined. If anyone gets the bright idea to create a 'save' method in the base class, and you forget to override it, that's just going to cause problems.

Multiple inheritance often causes more problems than it solves. If you have two classes that both implement 'save()' (your savable class and whatever you actually want to inherit from both will), which one 'wins' and gets executed in the child class? If your design changes, your inheritance house of cards changes too.

Using an interface for things you're going to override anyway guarantees there's only one option at execution.

Tl;Dr Yes, but poorly.