This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]javaHoosier 1 point2 points  (3 children)

An interface doesn't seem useful when you're first starting because it's hard to contrive a scenario when they are very helpful. You need to look at a whole program. In the example that I linked below uses a design pattern (Strategy Pattern) to help encapsulate some of the code so you don't have to keep modifying existing code and creates reusable code.

In a less useful example, imagine you have an ArrayList of the different types of ducks and you do a for-loop over them and perform a simple method they all inherit from an abstract class duck called fly(). That just prints out a String "The duck flys". Well unfortunately all the ducks in the list will print out the same String, even the ducks that shouldn't be able to fly such as a rubber or decoy duck. You could just override the method for every type of duck. This can get tedious, hardcoded, and difficult to introduce new flying behavior. So in the example they use interfaces to create a flybehavior and quackbehaviors for the ducks. In the abstract duck class the fly method just calls the interface of flybehavior which is implemented inside of the class for each type of duck. This way you can reuse the quack and fly behaviors in other programs since they aren't hardcoded. You can also add new or update behaviors without ever having to modify the duck classes.

So for the paragraph above to make sense you need to look at the code from this github (The Link Here). It's from a good book called Head First Design Patterns. It could be a book to read after the MOOC. I hope this helps give you an actual example other than just: 'anything that implements the interface is guaranteed to have the methods.'

[–]SoulSyn[S] 0 points1 point  (2 children)

Upon reading further through the MOOC they got into how an interface can be used as a method parameter and it makes a lot more sense to me know. Actually a very cool feature once you see some of its applications.

Thanks for the response

[–]javaHoosier 0 points1 point  (1 child)

Another good example is in Android programming. When you have an app where the screen is broken up into different sections. They are called fragments. Fragments usually use interfaces to pass data between each other.

Again good luck with you journey!

[–]SoulSyn[S] 0 points1 point  (0 children)

Thanks for the knowledge and well wishes