Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Last week my lecturer was teaching us about interfaces in Java.

However, I failed to understand her explanation that well.

Does anyone have a good description, or explanation of Java interfaces, and reasons to make use of them?

share|improve this question

marked as duplicate by jk., thorsten müller, Jalayn, Martijn Pieters, gnat Apr 9 '13 at 12:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

9  
Please google first. –  arnaud Oct 9 '11 at 20:51
4  
Talk to the lecturer about it. It'll help you to understand it, and help her to be a better teacher simultaneously. –  user25791 Oct 10 '11 at 3:26
add comment

4 Answers

Interfaces in Java define a contract specification.

Meaning, an arbitrary class X might depend on a feature expected to be implemented by interface Y, but doesn't necessarily care about how that feature is implemented, as long as it produces the result or process that X depends on.

So one could create another class Z to implement interface Y and pass it on to X.

This generates flexibility, as one could always choose to supply class X with a different, possibly more efficient, or specialized version of the feature implemented by interface Y.

Depiction:

class Customer {
  String name;
  int age;

  public Customer(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() { return this.name; };

  public int getAge() { return this.age; }

  public String toString(CustomerFormat format) {
    return format.formatCustomer(this);
  }
}

interface CustomerFormat {
  String formatCustomer(Customer customer);
}

class InlineCustomerFormat implements CustomerFormat {
  public String formatCustomer(Customer customer) {
    return String.format("%s, %d" years old, customer.getName(), customer.getAge());
  }

class SimpleCustomerFormat implements CustomerFormat {
  public String formatCustomer(Customer customer) {
    return String.format("%s-%d", customer.getName(), customer.getAge());
  }
}

One important thing to notice about interfaces in Java (and some other languages) is that nothing lets you enforce the actual protocol implementation, other than test code.

What I mean by protocol specification is that, when implementing an interface, you shouldn't only be saying "this will compile", but rather "this will compile and work".

In a nutshell, if you implement an interface, you should make sure that every code that uses that interface, will still produce a valid result if passed an instance of your class. That is part of the contract - which consists of both an API (enforced by the compiler) and the protocol (enforced by the developer's logic, or by tests).

share|improve this answer
1  
+1 for saying contract and specification - most answers that I hear to what an interface is "you say some class implements the interface and you have to implement the methods" without explaining the actual purpose it serves. –  Brandon Apr 9 '13 at 12:23
    
@Brandon Looking back at this post, due to your comment, I've now added an important note at the end of it. I'd like to hear if you find it helpful, as well. –  Yam Marcovic Apr 9 '13 at 14:46
    
Yes, great point. There is only so much that a compiler can enforce about how an object is used. But it's still important to, for example, open a connection before you close it. It's also possible to have an implementation that does not do what the interface says. Sometimes, the best specification is simply documentation. –  Brandon Apr 9 '13 at 14:54
add comment

As for the why people use it, there are two basic reasons:

  1. You might be writing an interface for which there are multiple implementations. The java.sql.* interfaces, for example, have different implementations that talk to different RDBMSes, and you load the one you want at runtime, so you can write your code to talk to any of them and just change the one line of code that loads the jar file.

  2. You might be making a "contract" between two programming teams. For instance, a co-worker and I were writing a new program as part of Kodak's now defunct digital cinema project. He wrote the front end, and I wrote the back end. But before we started, we defined an interface that would define all the calls that his front end could sent to my back end, and all the callbacks that I'd call when the operations were done or when operations happened on the backend. We could both start coding our respective sides of the interface, and write testing code to test our sides of the interface, without worrying if he'd implemented the same things as I had.

share|improve this answer
add comment

Interfaces are a concept that is very similar to, but essentially orthogonal to inheritance.

The basic difference is that java classes can only have one parent class; there is only one thing a derived class can inherit from. The problem with this is that sometimes you would want to use things that are too unrelated to each other to inherit from the same parent, but you want to use them for the same things.

Suppose you're modeling building materials; You have Glue for fastening things together, Caulk for sealing things, Shim for separating things.

Thing is, DuctTape can be used for all of these things. There's no way to have this useful material inherit from all three things; it must choose one.

What this suggests is that it should inherit from none of them; It should just be a specialization of Material and then tell the program that it "can do" all of those things.

Interfaces do exactly that; a java interface doesn't specify how any implementation actually does a thing, only that it can do that thing.

share|improve this answer
add comment

If you want a really simple explanation and a reason to use interfaces: think of them as buttons that you can press, and that you can apply to your objects. If you want to be able to call the same method on different objects, you can only compile your code if the compiler knows that method exists for that object.

The most simple example is the on/off button pairs for electronic devices. In Java, suppose you want to implement the following method:

void turnOnDevice(Device d) {
    d.turnOn();
}

And you have different Devices. The most efficiënt way to do it is to implement an interface:

public interface Device {
    void turnOn();
}

And then you can use it for either a TV or a coffee machine:

public class Television implements Device {
    public void turnOn() {
        //implementation
    }
}

public class CoffeeMaker implements Device {
    public void turnOn() {
        //implementation
    }
}

This immediately shows why you should not use inheritance: What does a TV have to do with a CoffeeMaker? If you need this kind of functionality and you're in doubt whether you need an interface or a superclass, just ask yourself: is (subclass) a (superclass)?

Test:

  • Is a coffeemaker a TV? => no* => interface
  • Is a car a vehicle? => yes => inheritance

*Although I can see this happen in some future

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.