Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.