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

Can someone please re-explain interfaces? I'm not wrapping my head around what they are and what they're for. I'm currently going through Java Data Structures.

1 Answer

Interfaces are in effect classes but they can have only abstract methods. No instance variables, no concrete methods, etc. Classes can implement interfaces. If they do they must make the abstract methods concrete.

Example. If Shape were an interface it could have an abstract method: public double getArea(double radius);.

If Circle implements the Shape interface it would need to make that method concrete:
public double getArea(double radius) { return Math.PI * radius * radius; }

Note that Shape couldn't be a class, as there is no formula for the area of a shape.

Why have interfaces? It's a way to have multiple inheritance without the big problems of multiple inheritance. Classes can extend only one class (superclass), but they can implement many interfaces.

There's much more that could be said, but those are the basics. Note that there are a number of good web sites that go into interfaces and inheritance in detail.

Thank you!