Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - The purpose of interfaces continued

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...