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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…