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

Jiten Mistry
Jiten Mistry
4,698 Points

What is the use of an interface?

I dont understand the use of an interface in java, could someone please explain why we would use it?

2 Answers

Allan Clark
Allan Clark
10,810 Points

An interface is a guarantee that a class will have certain methods. This is useful when passing arguments to methods. In code terms it will allow a method to accept arguments based on the interface rather than being restricted to objects of a certain type. For example:

       public void methodFoo (Set<Strings> someStrings) {
           doSomething(someStrings);
      }

This method is able to accept any argument that implements the Set interface (and then do something with it). That means it can take a TreeSet as well as HashSet. If had to do something similar without using interfaces we would have to duplicate code. The above example would turn into something like this:

      public void methodFoo (TreeSet<Strings> someStrings) {
          doSomething(someStrings);
      }

     public void methodFoo (HashSet<Strings> someStrings) {
         doSomething(someStrings);
     }

If you wanted more types of sets you would have to have more methods.

Hope this help!

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Jiten;

Welcome to Treehouse!

Great question. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.

Take a look at the official documentation and post back if you need more information.

Happy coding,

Ken