开发者

What is sense of interface?

开发者 https://www.devze.com 2022-12-22 09:58 出处:网络
I am still not so familiar with interfaces in Java. I know that interface tells which methods should have classes that implements that interface. But what is sense? Why to use it? Is not easier to cre

I am still not so familiar with interfaces in Java. I know that interface tells which methods should have classes that implements that interface. But what is sense? Why to use it? Is not easier to create instance of class that implements interface instead of instance of in开发者_运维百科terface? Or do I something important miss?


Try reading about "programming to an interface" and "inversion of control".


Many people use interfaces to define abstract classes - all the members of a class, without the explicit implementation. I frankly don't see a lot of value in that.

I prefer to use interfaces to do one of two things:

  1. Show the orthogonal capabilities of a class
  2. Declare the requirements that a class has

The second one is, I think, the more interesting, and probably deserves more explanation. You might write a class that requires teh ability to load or save some data. Rather than directly talking to whatever data store you'll use, you can declare an interface that has the methods you want to be able to call.

Then, implement a class that has those methods (implements that interface), and pass it to the class that wants it.

This gives you good abstraction and separation of responsibilities.


Java does not support multiple inheritance, but it does allow a single class to implement multiple interfaces.

This makes it possible to define functionality in terms of the expected "contract" a class should fulfil, i.e. "it must be enumerable, it must be serializable, and so on", rather than "it must be of this particular type".


An interface is essentially a contract guaranteeing that a given class will have the listed set of methods.

This allows you to just say that you have an object which happens to oblige to "List"-contract, so you know you have e.g. a "size()" and an "add(...)" method, which you can then just call.

This may allow you to hide immense amounts of complexity behind a simple interface. Just think of JDBC Connections...

0

精彩评论

暂无评论...
验证码 换一张
取 消