OK so I gather that Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance. Kind of like a contract. And I semi see the point of them.
But if all you have in the interface is:
public interface animal{ void eat(object food); }
and it has no implementation as such, then whoever uses your interface has to write it from scratch, every time.
If you are creating a number of classes all implementing such features and the implementation is only slightly different, this is going to be a lot of hard work.
Any help to get my head around this is appreciated because I know it’s really important.
Advertisement
Answer
Interfaces are the only way to create multiple inheritance in Java.
Say you create a class Animal
. And all animals, including humans extend that. And each of those animals inherits common methods like eat, breathe, etc.
But now let’s say you have a MathProblem
class.
And you want to have certain classes that can solve that problem by passing the problem to a solve(MathProblem problem)
method.
And you know that a Human
, but also a Computer
might solve the math problem. So they both need to be able to solve that problem. You might be able to get the Computer to extend some MathSolver
class that has the method, but Human already extends Animal, and can’t extends anything else. So a better way is to make MathSolver an interface and have both Human
, Computer
, and any other classes that need to solve problems implement that.
Also note that a Human
and a Computer
might solve the problems in completely different ways, since their such different objects. That’s what interfaces are best for. Defining certain abilities that cut across multiple inheritance hierarchies, and can have very different implementations, but can all be passed to a method that accepts any of them. Think of the Comparable
interface; it’s not something a certain class of objects has, all sort of things can be compared, and usually in very different ways. But you can always call sort on a List
of Comparable
objects since you know they have a certain order, no matter if they’re Numbers
, Animals
, Computers
or anything else (as long as they implement Comparable
and define their ordering).