r/javahelp • u/ProHoyah • Apr 18 '19
Solved What's the point of interfaces?
We've been learning interfaces in my class and I have a good grasp on the concept, but the thing that confuses me is what's the point? Your just writing more code as a blueprint to put classes in "groups". Maybe the code I'm writing is not large enough to make interfaces useful. Can some one help me in learning the use of interfaces. Thanks in advance!
7
u/slowfly1st Apr 19 '19
Contract
Interfaces define a contract, how code must be implemented. Check for instance the java.util.List interface: e.g. the add Method: Appends the specified element to the end of this list (optional operation). Now there's different implementation, the ArrayList, which stores the elements in an internal array, or the LinkedList, which "links the elements", instead of using an array. If you receive a List from a method, you (usually) don't care what the implementation is and you assume, the implementation is following the contract. And if you want to implement your own List, you have to follow the contract.
Frameworks / 'Callbacks'
Imagine you want to provide a library to someone and you have to somehow call his code. For instance you want to write an RSS feed poller, you write something like
class RssFeedPoller {
void poll() {
while(true) {
if(rssFeed.hasNews() {
RssNews rssNews = rssFeed.readRssNews();
// but what now?!?
}
}
}
}You then can simply provide an interface:
interface RssNewsListener {
void newsReceived(RssNews rssNews);
}
class RssFeedPoller {
RssNewsListener rssNewsListener;
RssFeedPoller(RssNewsListener RssnewsListener) { }
void poll() {
RssNews news = rssFeed.readNews();
rssNewsListener.newsReceived(news);
}
}
}
class ConsoleRssNewsListener implements RssNewsListener {
@Override
void newsReceived(RssNews news) {
syso(news)
}
main() {
new RssFeedPoller(this); // this because 'this' implements the interface
}
}Unit Testing
When writing unit tests, interfaces are used to mock away implementations. Let's imagine something like this:
class CallCenterIncidentSystem {
void addTicket(Ticket ticket) {
database.saveTicket(ticket);
if(ticket.isSuperHighPriority()) {
notificationSystem.sendNotification(ticket); // send a text or something
}
}
}Now the most important thing is, you don't want to send texts from your local machine, that's when we use mocks. (Actually, this would work without interfaces, but that's sometimes/usually a lot of pain)
OOP / Software Design (maintainable code)
There's lots of rules / principles in OOP which are usually achieved using interfaces. One of the most important one is the open closed principle: Open for extension, closed for modification. We use that principle (what we do is actually called "branch by abstraction") often.
6
u/Fritzzzz Apr 18 '19
https://softwareengineering.stackexchange.com/questions/131332/what-is-the-point-of-an-interface
-- pretty much typed out what this says, he does a better job.
3
u/prashant_jaswal Apr 19 '19
Interface is a specification. And the vendor provides the implementation.
For example - An ATM machine has some features like withdraw, deposit, balance enquiry and many more. While designing these features, ATM service provider described these methods in an interface.
Public interface ATMService{
void withdraw(double withdrawing Amount,long accountNo);
void deposit (double amount,accountNo);
double getBalance(account No); }
And they are expecting it's implementation from some vendor.
The reason it is said code to interface rather than the implementation, is because we are invoking the method through interface, later on if there is some changes in the implementation or if first implementation was in .net and now they want in JAVA,only the implementation will be changed, ATMService won't be bothered about it as it is communicating with interface and not the implementation.
And Also, you have implement multiple interfaces in your class but you can extend only one class.
Hope it helps
2
Apr 18 '19
A simple example is having different versions of the same class that retrieve data.
Let’s say you have a book data access class and so you create an interface that has methods for creating, updating, editing, and deleting books.
You implement the interface and have this implementation get the data from the database through sql queries.
Some time goes on and you now want to get the book data from a restful api. Well you can just have a new class implement the interface and now in the methods you connect to a rest api instead of the database using sql. You can be sure you’ve implemented the correct methods and you can simply switch out the original implementation for the new one, and whatever class was using your original implementation shouldn’t notice a difference, even though your new implementation gets the data in a completely different way. Everything that was using your original implementation will use the new one in the exact same way.
Same methods, different ways of implementing them.
2
u/ZeroGainZ Apr 18 '19
The same reason why everyone likes USBs, because whatever the class is, as long as it meets the interface, communication can occur between the two in a standard defined way.
2
u/Daedalus9000 Java Developer Apr 19 '19
Simply put, it separates how the pieces of a program interact with each other (interface) from how each piece of a program does its job (implementation). When I was in school I felt exactly the way you did, but once you start working on a sprawling and complex code base, it becomes much more clear why interfaces are a necessity.
2
1
Apr 19 '19
Maybe the code I'm writing is not large enough to make interfaces useful.
Without a doubt this is part of it. As the code gets larger it starts to make sense. The size code you are writing in school usually is just enough to show you understand the mechanics of it but is so small the "why" of things often gets lost. I recommend looking into some open source projects. It can help to start understand how things work with a larger code base.
1
u/Shadow_Mite Apr 21 '19
The simple way we learned it was through taxonomy. Public class dog interfaces mammal. Dog is it’s own class but it inherits everything from the mammal interface. In short, it’s one way to achieve polymorphism
-2
34
u/Talulabelle Apr 18 '19
The short-short, practical, answer is 'So you can have different types in the same collection'.
Let's say you have a bunch of different objects, but you want to put them all in a list, and then tell every object in the list to save it's self.
Without an interface, you'd have to have a different location for each object, and a huge method that finds every object that needs to be saved, and call it's individual save method.
If you just 'implements savable' and guarantee that, regardless of the type, it will implement the 'public void save();' method, you can put everything in a 'List<Savable> thingsToBeSaved' when you create it, and then have a method that calls 'save()' on everything in the list.
Tl;Dr; It lets us work with different classes as though they were the same type for, for a single, specific, purpose.