Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface advantages in Java

Tags:

java

interface

My question is simple: is there any advantage of using interfaces if they are implemented by a single class ?
I always thought that interfaces are good only when there are multiple implementations of that interface.

Thanks.

like image 814
Adrian Avatar asked Jun 30 '11 10:06

Adrian


People also ask

What is the advantage of interface in Java 8?

Another welcome benefit of Java 8 Interfaces is the ability to add new concrete methods to an existing interface, which has already been implemented, without breaking the program. Before Java 8, if you had a class implementing an interface but not using all its methods, that class would have to be labeled as abstract.

What is an advantage of using interfaces in your class design?

Using an interface is far more powerful than implementing one method in multiple classes, because if each class implements the same interface, you can treat them all the same (without casting).


1 Answers

In a word: no. The contract that an interface means can be specified directly in your only class.

If you are clear that you won't need another implementation of the same methods in the future, you can avoid defining an interface.

Of course, the issue here is "in the future" clause. If the project is small, without a long development/upgrade period, and well defined, you can be almost sure about what will be needed in the future.

If the project is long as is probably that it will be subjected to changes, then you will have to factor in:

  • probability that you finally need an interface.
  • probability that you know now what methods the interface will need in the future.
  • cost of doing the interface now vs. refactoring in the future.
like image 136
SJuan76 Avatar answered Oct 06 '22 00:10

SJuan76