10

Possible Duplicate:
The purpose of interfaces continued

I just started learning Java not so long ago.
I've come across Interfaces which I know how to use but still can't quite grasp the idea of it.
As I understand it, interfaces are usually implemented by classes, which then have to implement the methods declared in the interface.
The problem is - what exactly is the point? Wouldn't it be easier to just implement the methods from the interface as normal class methods? What exactly are the advantages of using interfaces?

I've tried looking for an answer on google. There were many but I still couldn't understand the point of it. I also read this question and its answers, but the whole contract thing just makes it more complicated...

Hopefully someone could simplify it good enough! :)
Thanks in advance!

Community
  • 1
  • 1
Asaf
  • 2,005
  • 7
  • 37
  • 59
  • 6
    This has been asked a lot before! But you asked it a lot more politely than most of them! Congratulations! – Ry- Dec 25 '12 at 21:11
  • Though perhaps a better question would be one where you delineate what *specifically* confuses you about the tutorials and posts that you've read. That way we don't see a re-hashing of the same old thing, and you get better help. – Hovercraft Full Of Eels Dec 25 '12 at 21:30
  • 1
    You might try the Java Glossary for interface information .... http://mindprod.com/jgloss/interface.html –  Dec 25 '12 at 21:24
  • http://stackoverflow.com/a/24436493/1286942 – Jo Smo Jul 27 '15 at 03:26

9 Answers9

12

An interface allows you to provide a different implementation at runtime, inject dependencies, separate concerns, use different implementations for testing.

Just think of an interface as a contract that a class guarantees to implement. The concrete class that implements the interface is irrelevant. Don't know if this helps.

Figured some code might help. This doesn't explain everything there is more to interfaces, keep reading but I hope this gets you started. Point here is that you can vary the implementation...

package stack.overflow.example;

public interface IExampleService {
void callExpensiveService();
}

public class TestService implements IExampleService {

@Override
public void callExpensiveService() {
    // This is a mock service, we run this as many 
    // times as we like for free to test our software

}
}

public class ExpensiveService implements IExampleService {
@Override
public void callExpensiveService() {
    // This performs some really expensive service,
    // Ideally this will only happen in the field
    // We'd rather test as much of our software for
    // free if possible.
}
}


public class Main {

/**
 * @param args
 */
public static void main(String[] args) {

    // In a test program I might write
    IExampleService testService = new TestService();
    testService.callExpensiveService();

    // Alternatively, in a real program I might write
    IExampleService testService = new ExpensiveService();
    testService.callExpensiveService();

    // The difference above, is that we can vary the concrete 
    // class which is instantiated. In reality we can use a 
    // service locator, or use dependency injection to determine 
    // at runtime which class to implement.

    // So in the above example my testing can be done for free, but 
    // real world users would still be charged. Point is that the interface
    // provides a contract that we know will always be fulfilled, regardless 
    // of the implementation. 

}

}
0909EM
  • 4,761
  • 3
  • 29
  • 40
  • So basically every variable that is from an interface type (`IExampleService`) in this case, must/does include the methods declared in the interface right? If so, that means the(one) usage of interface is "bringing together" all classes that have a common method right? Also, can an interface variable 'contain' every object or just those that implement it? – Asaf Dec 26 '12 at 10:05
  • Every object that implements an interface implements all the methods on the interface. Think of that as the contract. An interface doesn't bring together classes. I don't think u can access object data from an interface variable but the interface variable will provide access to the interface regardless of what the object is... clear as mud? – 0909EM Dec 26 '12 at 11:15
11

Interfaces can be used be used for many things. The most commons uses are polymorphism and dependency injection, where you can change the dependencies at run time. For example, suppose you have an Interface called Database which has one method called getField(...).

public interface Database 
{
    public void getField(String field);
}

Now suppose you have use two databases in your application depending on your client: MySQL and PostgreSQL. You will have two concrete classes:

public class MySQL implements Database
{
    // mysql connection specific code
    @Override
    public void getField(String field)
    {
        // retrieve value from MySQL
    }
}

And...

public class PostgreSQL implements Database
{
    // postgre connection specific code
    @Override
    public String getField(String field)
    {
        // retrieve value from Postgre
    }
}

Now depending on your client preference, you can instantiate a MySQL or PostgreSQL class in your main

 public static void main(String args[])
 {
     if (args[2].equals("mysql"))
         Database db = new MySQL();
     else
         Database db = new PostgreSQL();
 }

 //now get the field
 String foo = db.getField();

Or you can use Factory/Abstract Factory or scripting engine with JS or Ruby.

goblinjuice
  • 3,184
  • 24
  • 26
4

They're for implementing polymorphism without requiring the use of inheritance.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    Ah, but they *are* a form of inheritance. Perhaps you meant without class inheritance? – Hovercraft Full Of Eels Dec 25 '12 at 21:17
  • "Class inheritance" is the only form of inheritance that matters. Everything else is faff. – Ignacio Vazquez-Abrams Dec 25 '12 at 21:21
  • @HovercraftFullOfEels I'm aware of inheritance among interfaces, but in my lingo, a class *implements* an interface, it doesn't inherit from it. Both are forms of *subtyping*, yet, but that's yet another concept. –  Dec 25 '12 at 21:23
  • 1
    I respectfully disagree. Interfaces represent pure *types* and interface inheritance represents *type* inheritance. Something important, powerful and practically useful. – Hovercraft Full Of Eels Dec 25 '12 at 21:24
3

The idea with interfaces is that they specify a contract that a class can implement. This idea is largely covered in the other post that you read.

The reason that just implementing the methods from the interface directly isn't enough is that other methods can use the interface type to require that those methods are present.

Let's use AutoCloseable as an example. The only method is a close method, but it's much easier for a method to express the thought "I need a parameter that can be closed" using the type than listing out all of the methods:

public void passMeSomethingThatICanClose(AutoCloseable bar) {
    //stuff goes here
    bar.close(); //the compiler knows this call is possible
}

If we didn't have the concise type name, the method would have to list the requirements explicitly, which wouldn't be very easy, especially when the interface "contract" has many methods.

This works the other way as well. By having a specific keyword "implements AutoCloseable" to signify the intention, the compiler can tell you if you haven't implemented the contract correctly.

public class BrokenCloseable implements AutoCloseable {
    public void colse() {  //ERROR — see the typo?
        //blah
    }    

}

This is an error, because the method has the wrong name. In Java, the compiler can (and will) tell you this. But if you were just responsible for implementing the methods yourself, you wouldn't get an error. Instead, your class would just silently "not be" autocloseable.

Some other languages (Python is a good example) don't do things this way — instead they do things the way you've suggested in the question. This is called "duck typing" (if it looks like a duck, and quacks like a duck, treat it like a duck), and it's also a viable way to do things, just different from Java.

Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
2

Interfaces specify functionality. In a way, they provide multiple inheritance. Let's say I have a function that does something with a list. But not just a list, just any collection. Anything that I can loop over the contents. So I use the interface Iterable.

public int randomMethod(Iterable<Integer> li) {
...
}

Now this works with Lists and HashSets and all different things which are implemented and work in completely different ways and belong in different class structures, but all provide this basic functionality. This is different from say, a big game loop that .update()s all entities that extend a common class, although an interface could be used.

Raekye
  • 5,081
  • 8
  • 49
  • 74
2

Take the List<T> interface, for instance. You can decide at only one point whether you want to use an ArrayList<T> or a LinkedList<T> (or something else related) for a specific occasion.

Yet they both implement the List<T> interface. So, no matter how they work or whether they're even related hierarchically, it is guaranteed that they expose a set of methods you can use and you don't have to know at every point in your code the implementation behind the collection object you end up with.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
2

Because of "The Deadly Diamond of Death". Lets consider this situation:

You write class (name: Parent) in programming language where multiple inheritance is allowed. That class contains one instance variable ( int a;) and one method (void hello()). Then you create two classes (Kid1 and Kid2). Every of that classes extends Parent class. Then you override hello(); method in both Kid1 and Kid2 classes and you assign some value to a variable, also in both Kid1 and Kid2 classes. In last step you create 4th class (like Main) extending Kid1 and Kid2 classes (multiple inheritance). Now...question is, which of hello(); methods will Main class inherit and which value of a variable.

Since there is no multiple inheritance in Java, we have interfaces... abstract classes containing abstract methods. We can implement multiple interfaces, but under condition we have to override all methods which implemented interface contains.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
1

I would advice you to take a look at Strategy Pattern and Composition Pattern.

1

Your question is way to broad to answer in a single post without being either too contrived or too generic without being useful. So I'll attempt to give a hopefully meaningful example of when interfaces are very useful.

Say you have a number of classes which represent various types of objects.. Maybe a dozen, or any sufficiently large number. And you have some function in another class which would like to be able to order arbitrary objects. For that it would need to be able to compare any two objects and determine if one is greater than, or less than another. Since each object could be of any one of your many types of classes this compare function would be pretty tedious to write since it would have to determine what type each object was and then do the comparison by invoking the appropriate logic for each class.

Enter interfaces. At this point, you could just have all your classes implement an interface such as Comparable which specifies that any class implementing it will implement a Compare method.

Now your function that orders object would become trivial to write since it can just rely on the fact that any class of object it needs to compare would have the same Comapre method.

This is just an example - and a rather common one at that.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • So basically, what you're saying is that interfaces are used to "add" some kind of common method to all Comparable objects? (Obviously the developer would first have to implement the compare method from the interface). How would you check whether an object implements an interface or not? I've also seen this used a lot when referring to interfaces `someInterface a = new someClass();` ? I partially get what it does, but why is it needed if the function is implemented in the class itself? Thanks for your answer, by the way, I understood it the best! :) – Asaf Dec 26 '12 at 09:47
  • @xTCx - To test whether an object implements a certain interface (or is of a certain type) you can use the **instanceOf** operator - read more about it on the web. I'm glad you found my example useful! – Mike Dinescu Dec 26 '12 at 15:30