DEV Community

Gabriel Babler
Gabriel Babler

Posted on

What is an INTERFACE in JAVA? w/ examples

Hey folks! In today's post, I would like to talk a little bit about INTERFACES in Java. Let's go?

So, trying to be as basic as possible, we can start by saying that an interface it's nothing else than a contract.
That's it!
Do you know when you are opening a new bank account? Or, when you are signing your new rent house? What are they? Contracts!

Basically, they are pre-defined conditions that you need to accept if you want to use them. Do you think it makes sense?

Taking that to the programming world, when we define a new interface and add on it some methods, for example:

Image description

Here, I am saying that, in case anyone wants to use the interface Bank, the class is forced to implement the methods withdrawn and deposit, for example:

Image description

For the BankA to be able to implement the interface Bank, it needs to implement the methods from Bank and add your own logic to them. Otherwise, Java will complain.

Also, you can notice the annotation @Override. In Java, that's the way to implement the methods from the interface.

Another good thing about the interfaces is they allow us to use polymorphism in Java, where I can use the reference of the interface for every class that implemented it.
Plus, it follows one of the S.O.L.I.D principles - the letter O which stands for Open-Closed Principle. That means the class should be open for extension and closed to modification.

First, let's see a bad example:

Image description

Here we can notice how hard it will be to extend the class if we need to implement new banks to our application, right? Every time I'll have to add a new dependency to my BankService class and implement a new method.
How can we avoid it? Interfaces!

Look at this:

Image description

The code is doing exactly the same thing, but now it's easy to extend the code. I just need to pass the implementation I want to use:

Image description

When I create a new instance of BankService I pass as an argument the implementation I want to use, in this case, BankA. And, if I need to implement a new bank, it's as just simple:

Image description

And then use it:

Image description

Pretty simple, don't you think?

That's it for today, folks! I hope this article can help you to better understand the interfaces and how to use them to write better code =)

If you have any questions or suggestions, feel free to leave a comment =)

See you next time.

Top comments (0)