Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Interfaces in Java Interfaces in Java The Interface Advantage

Kevin Langmade
Kevin Langmade
13,896 Points

What is the usefulness of Interfaces?

In this video, the Interface Advantage, we created a new interface so that the method of sellGoods() would be connected to something other than a class that wouldn't make much sense. However, in an interface, you can't add information to the body of the method.

What is the point of interfaces? Is the only purpose a way to force a new class to implement specific methods to make sure they are uniform? It seems like either way you have to @Override the method anyway. How is it saving time or keeping your code DRY?

1 Answer

alastair cooper
alastair cooper
30,617 Points

An interface can be thought of as something that an object can do. consider the following:

I am a person. If you were to model me in code you would probably build a person object and define all my properties. But not all people are the same. We can all do different things.

I am a teacher. You could break that down into 3 basic jobs (methods in code) - Plan lesson(), Teach lesson(), Mark Books(). Not all people share these skills, so you might make a sub-class (inheriting from Person) that had these 3 methods

My boss (or the program that called me) doesn't care about my properties, whether I am English, Russian or from Mars, They don't care if I have 1 leg or 3 eyes. They only care that I can IMPLEMENT my 3 methods. Any object that can IMPLEMENT the teacher interface PLAN() TEACH() MARK() is ok for their purposes. For Instance, Treehouse is not a person object, but a computer program (albeit run by great people!), but it can still implement those 3 tasks and would be fine for the purposes of the calling method (or my boss when I am off sick).

The usefulness of an interface is about polymorphism. It allows any object to be used in place of another as long as it has the required methods.

A more code based example is the OnClickListener. Pretty much any view can be clicked (because they implement the OnClickListener interface. Doesn't matter what view it is as long as you override the onClick() method (the contract made by implementing the interface)

hope this helps