Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are interfaces used in Java when each method must be typed out again in the actual implementation?

Tags:

java

interface

Why are interfaces used in Java when each method must be typed out again in the actual implementation? What's an example of a situation where writing out an interface makes things easier?

like image 263
mango Avatar asked Jan 12 '23 11:01

mango


1 Answers

Interfaces define a contract, not an implementation. This allows you to divorce yourself from the actual implementation of an interface- as long as the implementation satisfies the contract, you're happy.

Say you call a method that returns a List (which is an interface). You can use that List because you know it has List functions like get() and add(). You don't have to worry about what kind of list it is. If the List happens to be an ArrayList and then the method changes to return a LinkedList instead, you don't have to change your code at all, since both are guaranteed to have the List functions.

like image 130
Kevin Workman Avatar answered Jan 25 '23 06:01

Kevin Workman