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

Hey, I have forgotten what a Java interface is.

Hey,

Would someone be so kind as to pick my brain as to what an interface in Java is.

Many Thanks,

Richard.

3 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Think about them like a contract. Classes use the keyword implements and are then required to implement all the methods.

When you declare a variable, it is best practice to declare it using the interface that it implements because then you can later change the implementation.

That help bring it all back?

A Java interface is like a class except that it has no instance variables, no constructors, and all its methods are abstract.

Why have them? If a class implements an interface it is promising to implement (make concrete) those abstract methods.

For example, Shape couldn't be a class if it has a getArea() method because there is no area formula for a generic shape. Instead, Shape could be an interface with an abstract getArea() method, and require any implementing class, like Circle or Rectangle, to make that abstract class getArea() concrete.

Note, there are folk who would argue that Shape should be an abstract class rather than an interface, but that is another story. The example still holds.

Hello,

Thank you both, this has really brought it back for me.

Many thanks,

Richard.