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

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