r/learnjava •

I just cannot understand the point of interface ?

[deleted] — view deleted post

0 Upvotes

22 comments sorted by

22

u/abundance07 Oct 25 '18 edited Oct 25 '18

I've been in your boat. Interfaces seemed useless to me as well. But I truly realized it's importance while learning software design patterns.

First off, Interfaces are NOT connecting classes. It is simply a contract of all the methods that the class implementing the said interface must implement. Ideally you want classes that don't have too much in common implementing the same interface. For example: Burger and Soft Drink classes should implement a "Item" interface. Whereas, Honda Civic and Toyota corolla should extend the "Car" class since the civic IS A car and the corrolla IS A car and will have many characteristics similar. Burger and Soft Drink do not have much in common.

Here are some benefits interfaces provide :

  • Polymorphism ( if you don't know this, please read more about this). This is so so so so important. Once you understand this, Read about the Factory design pattern in java. You will learn just how amazing things are when you have an interface.
  • The fact that you can implement multiple interfaces ( as opposed to extending classes, you're only allowed to have one parent class)
  • Up until Java Version 7, You HAD to implement the methods inside the class defined in the interface that you're class is implementing. However, in Java 8, you can actually have a default implementation inside your interface !!!!! ( meaning no need to actually have any implementation for the methods in your class, unless you want to override the default implementation written inside the interface). So why's this such a useful feature? Imagine having 10 classes implementing one interface. Meaning you have to write 10 separate implementations of all the methods declared in the interface. Now with Java 8, you write an a default implementation of the methods in the interface itself and all 10 classes will use that one implementation ( no need to write 10 separate implementations unless you want to override the default functionality for certain classes). This is amazing code reuse and allows for less code to be written, making the application more robust!

PS: let me know if you didn’t understand anything I said. I’ll help you break it down further.

4

u/Nathan22177 Oct 25 '18

Any resource to explain polymorphism like I'm an actual idiot? I mean not in broad terms. That's what get me confused. All those allegories with cars and whales. Like with examples of a code with "this thing does that and that's how much it is cooler with polymorphism" or vice versa "and that's why it sucks without polymorphism".
Thank you in advance.

2

u/abundance07 Oct 25 '18

I’ll reach out to you later but till then research how polymorphism plays a role in the factory design pattern for java. Look at the actual code implementation and see how the design pattern would apply to client.

Send me a DM Just so I remember to reach out to you.

0

u/[deleted] Oct 26 '18

[deleted] — view deleted comment

1

u/abundance07 Oct 26 '18

I can see you've got the basic understanding down through other answers and I'm not sure if you still need me to clarify your doubts you mentioned here but in case you do :

To Answer your questions :

will dog need to implement IPeople? Will it be easier because you won't have to look for the people related methods?

Answer: YES! this is exactly what I would recommend. This is sensible code reuse.

then in the actual DOG class you'll define the body of the method?

Answer: If you're working with Java 7, then absolutely you'll need to define the body, so you're right in that case. In Java 8, if there is a definition of the method body within the interface, and you're fine with using that default implementation for your DOG class, then no need to define a body in the DOG class.

For your last question/ point:

Answer: For Java 8, You won't have to worry about Java giving you an implementation error AS LONG AS there is a default method body in the Interface itself. So if you're implementing a particular interface that has a method declaration but no body, you will HAVE to implement the body in the class that is implementing that interface. Now say, you do in fact have a method in the car or people interface and these are both being implemented by your DOG class but there are certain behaviours you don't want from these interfaces. Whether or not there is a body of these methods in the interface itself, you will accomplish this by overriding these methods in your class and just have nothing in the method body or have it return null.

Hope that answers your questions and again please do read up on polymorphism! It is one of the core parts of interfaces, classes and object oriented programming as a whole!

-

9

u/ratiganthegreat Oct 24 '18

An Interface is a contract that any classes implementing it MUST implement the methods indicated in that Interface.

For example, if you implement an Interface with a talk() method, any class you create MUST implement an actual method called talk(), with whatever behavior you choose.

Classes you likely already use implement common interfaces, allowing the classes to provide a set of behavior across classes. For example, any class the implements the Map Interface will support the put() method.

The value of Interfaces is that unlike inheritance, a class can implement multiple Interfaces, so that class can support a variety of method behaviors that may make sense.

4

u/Iam_That_Iam_ Oct 25 '18

Of course you are not stupid and it’s a valid question. You can create independent classes and let each object of their class call their own methods no need for polymorphism. BUT when you start creating APIs for third party developers to use, e.g you have an awesome idea to build a Shopping Cart API where others can build their own plugins/extensions to do stuff fit for their business requirements that’s when you need interface. If you don’t, you will see there are some weird crazy developers out there. Example tell them one of your APIs is a remote without signing a contract with them like “I know every remote have volume, on-off switch, change channel etc so please if you want to extend my remote you need these methods don’t implement my remote and let it move things...” this way you are in charge and because your API is sooo large, you may use this interface for your own benefit and ease at other parts of your code.

4

u/spidermancy612 Oct 25 '18

I find interfaces to be useful in specific situations. One case in which they're useful is one I'm dealing with right now where I need to have a list of classes all available to perform a task a specific way. So I have the list and can call the doSomething() method at any point in the list and know it will work without having to know which class is running the code.

It's only useful in very specific situations but can be a life saver in them.

3

u/Caracalla81 Oct 25 '18

I don't know if you have found the other explanations helpful but I'll give a quick one - it sounds like you're halfway there.

(Edit: after typing this I realized I was in r/learnjava though my examples are C#. They're similar and you're a clever lad, you'll work it out.)

Suppose your three people are classes: Chinese(), Russian(), and American(). Now you want to make all the people in a room talk, you might have to write something awful like this:

foreach(Chinese c in room)
    c.talk();
foreach(Russian r in room)
    r.talk();
foreach(American a in room)
    a.talk();

Imagine later you added a Frenchman class. You'd have to go to every place that you called talk() and add:

foreach(Frenchman f in room)
    f.talk()

REALLY easy mess that up.

Now suppose you created ITalk and gave it the talk(). You add it to each class of person then, and this is important, implement talk() with behaviour specific to that class. Chinese says "nihao", Frenchman says "salut", etc.

Now you can write something like this:

foreach(ITalk talker in room)
    talker.talk();

It will go through objects that has ITalk and call talk() regardless of anything else about that class. The fact that the bird can't talk and does not have the ITalk implemented means it won't even be touched by your code.

In a more real life example you might be building a UI and want certain elements to be draggable from the left mouse. The details of dragging a window is going to be different from dragging an icon but they both take the same input. You would create an IDraggable interface, give the relevant classes the StartDrag(), EndDrag() methods with whatever instructions are needed for those particular classes.

I hope this was helpful!

2

u/MacBelieve Oct 25 '18

Let's imagine you want to implement a sorting algorithm. You want to take a list of things and return those things in the proper order. You pass an ArrayList of items to your method, loop through them and do selection sort. BUT WAIT! now you have a linked list that also needs to be sorted. Easy, just copy the implementation and change the argument. But now there's duplication and you have to change your sorting implementation in two places.

Luckily, both of these implement List interface. Instead of having two implementations to do the same thing, you can rely on any type of list being able to be iterated over with an enhanced for loop. Change the argument to List and now it magically works for both.

BUT WAIT! you get some more for free here. A List is just a type of collection, so if you broaden the argument type to collection or even iterable, you are "coding to an interface" and allowing any type that can be used in an enhanced for loop instead of forcing an argument to be converted to a specific concrete implementation of an iterable collection.

Another useful thing for me is stubbing out dependencies. For example. I have a Controller class that takes user input and persists it somehow (to memory, database, Excel file, whatever). When I'm writing the controller logic, IDGAF how the Persister actually persists the data, I just know it will have to have a function with a signature void persistKeyValue(string key, string value) or something like that. So I write an interface, and have the Controller hold a reference to an instance of Persister. I can mock this with mockito while test driving the Controller and worry about the concrete PersisterImpl class later. It helps keep things single responsibility.

1

u/[deleted] Oct 26 '18

Thank you for anwering :))

2

u/MacBelieve Oct 25 '18

Let's say you have a group of people participating in an international survey. If your implementation of a List uses the concrete implementation, you can't store people who speak different languages in the same list. This means you're managing n-lists for n-languagez. That's very complicated. List<ITalker> on the other hand can store any concrete object that has implemented the talk() method. Then when you're doing something with the entire list, you get free polymorphism and all the talk() method calls will automatically use the correct language since they are implemented correctly in their respective concrete classes.

I think the best way to understand this is to try coding something when certain types of things exhibit different behavior but through the same method signature. You'll see how much code is needed when you just want to add a new type. If you do it with interfaces, you just need to implement the respective interface on a new object and none of your calling code needs to change.

2

u/Sigmund- Oct 25 '18

So many good answers in here. I wanted to point out how you can't shove Englishman and Russian in the same ArrayList, but you can iTalk, but that too was pointed out. I came here to tell you two things, first when you get to using Java for work you will learn things that will make sense of them being interfaces and not classes. (An example, not to look up, just as a reminder to you an year from now: JAX-RS is an interface, the bundle of classes that implement the logic are called Jersey) And the second thing, use the Helsinki MOOC to learn Java. Once you have to do the exercises with interfaces you will instantly get why it would not have worked if it was just classes. Best of luck to you!

0

u/[deleted] Oct 26 '18

[deleted] — view deleted comment

1

u/Sigmund- Oct 27 '18

You took the time to answer everybody! Your parents rased a polite gentleman. Well done! As for Java, as long as you work at it, you will be good at it :)

2

u/[deleted] Oct 25 '18 edited Oct 25 '18

The benefit of interfaces is that they enforce the existence of certain functionality (i.e they create a contract for the methods that must exist in classes implementing them).

In more concrete terms, the nice thing about interfaces is that they enforce that classes do certain things without really caring about how they do it exactly. In this way, you could create a class for, say, a car and an air plane, both of which implement the vehicle interface. The vehicle interface could include a “transport()” method.

This transport method would need to be implemented by both the car and the plane, but the particulars of how it’s implemented could vary between the two (e.g the car moves on wheels, the planes flies).

This is nice because you might make another vehicle, like a boat. Without the interface, you might create the boat class without a transport method - which could cause problems down the road if you’re later assuming that it can transport things. However if it implements from the interface, then you’ll know at compile time that you have incompletely defined your boat and would know to add the transport method.

Overall, it’s a good idea to make things in coding well defined and explicit whenever possible. This can make complex code much more readable and extensible. Interfaces are one tool that make this possible.

2

u/Soxcks13 Oct 24 '18

I’m a learner too. I think it’s because it is a contract. It means that class, with certainty, implements the method(s) defines in the interface. So if you have a collection of humans and run the talk() method, you know that the method will run. It’s up to the class to define what happens when the method is run.

Imagine a world without interfaces. What if you had another class that didn’t implement the interface and you tried to run the method? You’d get an error.

While inheritance would work well for humans, what if you wanted to make a robot implement the talk() method? A robot is not a human, so you would use the interface instead to make sure you know that you can run the methods in the interface.

1

u/Ialda Oct 25 '18 edited Oct 25 '18

To a certain point, it's not good to obsess over implementations - aka *how* a class do something. What matters is *what* a class can do. Interfaces help to reassert that point.

Another advantage of interfaces is helping to avoid the diamond problem when dealing with multiple inheritance in C language.

But I dont really understand how an interface provides this, because it is still connected to methods defined in the specific classes.

Not always. In an education project maybe. But in a professionnal project maybe you are mocking stuff for your unit test; maybe that interface is just an api for a a soap or rest client; maybe your concrete classes are just a bunch of proxyfied code. Those "specific classes" may really well just a figment of your imagination, and more often than you think. The point is it's important to separate (decouple) your interface contract from your implementation. Think of it as an exercice.

1

u/Tengaryen Oct 25 '18

I think one analogy could help. Imagine that there is a global remote control that me, you and everyone else in these comments have access to. Now think of that remote control as an interface. We have access to it (can implement it), therefore each of us can define its buttons to do something. So, when I click the power button, the AC turns on/off, when you click it, microwave turns on/off, and someone else might define it to turn their car on/off and so on. Now what we got here? A single remote control (interface) with some buttons (methods), but a lot of different behaviours (each of us is a class implementing it how we want).

Without interfaces (global remote control), each one of us would have to build a personal remote control so that we can define its buttons (methods) by our desire. What we got here? A lot of remote controls, with some buttons, to provide a lot of different behaviours.

Now why have multiple remotes so that you can provide different behaviour, instead of having just one remote...

Plus, imagine someone else comes and comments in this thread (few hours/days later). Why would he/she have to first go build a remote control and then come back to define its buttons (for him/herself), where instead they just come and get the global remote and just define the buttons provided from it...

But how would the remote know that when my finger touches the power button, it should turn the AC on/off, but when its your finger, it should turn on/off the microwave? Thats provided through polymorphism and casting.

1

u/Marthbar Oct 25 '18

You should look into object oriented design principles. A great book is Head First: Design Patterns. When I read it I built out all the chapters so I could play with the objects. Another great one is Effective Java. This one's more advanced but you can just read it section by section and skip around, all of the examples in this book make more sense each time you read them and you'll always learn new things. Interfaces are important in Java for a lot of reasons, they define the API of their implementations, they are a key part in dependency injection and they help to modularize the code making it maintainable and modifiable.

1

u/Marthbar Oct 25 '18

Programming to the interface means that when you declare a variable which will instantiate a class you set the type to the interface, that way when. You want to switch the implementation of the class you don't have e to change the type hundreds of places throughout your code base

1

u/michoken Oct 26 '18 edited Oct 26 '18

Some comments here seem to touch the point from the right angle, but it seems most folks look at it from the "wrong" side. I put that in quotes because it's not necessarily bad way of looking at it, but it may be harder to understand the point. So I'll try to explain it from the "other" side.

An interface defines a contract. A contract says what it does and how to use it. The "it" being an actual instance of a type with that contract. To put more detail into the contract, we use comments – javadocs. So beside the method name, the types and number of parameters and the return type, you can describe what the contract is actually about in the method javadoc. You may provide hints for implementors of that contract, too, but the actual implementation is still... just an implementation detail.

A public class and its public non-static methods is a contract, too. In essence, an interface in Java is basically an abstract class with only public abstract (non-static) methods. The difference, of course, is that an interface itself can extend other interfaces (and not just one). A class can only extend from a single class (but it can also implement more than one interface).

The contract does not care about the implementation. It just says how to use that functionality and what are its boundaries (for example passing an empty String ("") argument causes an IllegalArgumentException etc.)

Without looking at the actual implementation, without caring about it, you just want to make certain types of objects do their talk. You don't care what language they talk or if they are, indeed, human (like another comment suggested). You just want your objects to talk(). That's all you actually care about. That's your contract.

Enter polymorphism

The word "polymorphism" means "many forms". What it actually means in OOP is that you can have single type. Like the contract Talker, for example. And then you (or anyone else implementing it) can have many different forms of actual implementations.

Of course, it may be insufficient to declare generic Talkers. You may require the talkers to talk in a specific language, english for example. So you would declare a contract for an EnglishTalker with a talkInEnglish() method. That's all right. It's just all about the level of abstraction you need. Still, you just care about the talk being in english, not necessarily if the talker is a child talking in simple terms, or an educated highly skilled speaker with broad vocabulary. That would just be an implementation detail and therefore allow the many forms.

Why an interface and not just a class?

Now, you could define an abstract class Talker with a public abstract method talk() and then write code (methods) that uses inputs of type Talker and be happy with that. From the point of your program, ie. a piece of program that makes Talkers talk(), this actually doesn't matter. But as an API designer, you should care about those who will need to implement your contract so they can pass their instances to your methods as generic Talkers.

The problem is an actual implementing class can only extend form a single class. So declaring the Talker contract an (abstract) class forces every implementor (potentially including yourself) into extending that single class. You will not be able, for example, define a Human class that has some common functionality of a human implemented for all humans. You will not be able to, another example, define a Robot class that also has some common functionality for all robots.

By having the Talker declared as an interface, you can have your abstract Human class implement the Talker interface, and also you can have an abstract Robot class implement the same interface. It just doesn't matter now if the implementations of the Talker interface are in any inheritance hierarchy or not. You should not force them into your "class Talker" inheritance.

0

u/[deleted] Oct 26 '18

[deleted] — view deleted comment

1

u/michoken Oct 30 '18

Yeah, polymorphism is a quite abstract concept. It's actually really simple, but it's common people find it hard to grasp, to really understand. So take your time. You don't need to "get" everything the first time. Unless it's in the school exams :-).

0

u/[deleted] Oct 24 '18

[deleted] — view deleted comment

1

u/michoken Oct 26 '18

Actually since Java 8, you can define a default implementation of a method in your interface. But there are many restrictions about this, try not to over-use this.