7

Interfaces consists of abstract methods and final variables. Well, it is used as a generalized contract put forth so that classes implementing it should follow the rules by implementing methods in it.

Is this the only use/scope of interface in Java? Have they introduced the concept of interface only for this, or am I missing something? Please help me in understanding the use of interfaces, with examples. (Not on how to use or create interfaces, but to show how they are helping programmers).

Thank you.

gprathour
  • 14,813
  • 5
  • 66
  • 90
Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
  • 1
    I don't know if it is exactly an answer, so I'll comment. `interface`s are crucial in java because you don't have multiple inheritence. If you want your class to be `Iterable`, but also you want in to implement a certain logic, you cannot inherit from 2 classes, thus you will have to use interface. So, if you need more then 1 logic to be implemented by a class [which is not uncommon], You cannot use only `abstract` classes, you'll have to use an `interface`. – amit Jan 25 '12 at 08:05
  • Possibly duplicate of http://stackoverflow.com/q/8531292/1055241 check out the accepted answer to understand the concept of interfaces. – gprathour Jan 25 '12 at 08:11
  • @Ajj: Then, I added it as an answer. – amit Jan 25 '12 at 08:13
  • Thats a good link GP, thanks !!! – Anuj Balan Jan 25 '12 at 08:19
  • @Ajj: 300 000 lines Java codebase where there isn't a single *abstract* class and where all the classes are *final*. In other words: we do not believe in *"code reuse through implementation inheritance"*. We consider that Java supports multiple inheritance because the *only* kind of inheritance we have in our codebase is interface inheritance (and liberal use of multiple interface inheritance). **Any** OOA/OOD (including the ones using multiple inheritance) can be translated to Java using interface inheritance. We much prefer delegation over concrete implementation inheritance... – TacticalCoder Jan 25 '12 at 08:47

11 Answers11

9

Here's where I understood their usage when I first read about them:

Say that you receive a portable disc player as a gift. When you try to operate the player, nothing happens --- the player requires batteries. What batteries fit into the player? Fortunately, on the back of the player is the specification, This player requires two AA batteries.'' With this information, you can obtain the correctly sized components (the batteries) and fit them into the player. The completed assembly'' operates.

The specification of the disc player's batteries served several useful purposes:

The specification told the user which component must be fitted to the player to ensure correct operation. The specification told the manufacturer of the disc player what size to build the player's battery chamber and what voltage and amperage to use within the player's electronics. The specification told the battery manufacturer what size, voltage, and amperage to build batteries so that others can use them. These three facts are important in themselves, but they also imply that the user, the disc manufacturer, and the battery manufacturer need not communicate directly with each other --- the specification of the battery is all that is needed for each party to perform its own task independently of the other two.

isah
  • 5,221
  • 3
  • 26
  • 36
  • 2
    This is a great example. You could think of the battery brands as concrete implementations of the battery type interface. You could think of Energizer, Duracell, and Sony as all implementing the AA interface. The connections of the battery is the same and the output is the same, and of course the size, but the branding and perhaps some subtle internal components are different. +1 – jamesmortensen Jan 25 '12 at 08:27
5

I will give you an example.

You have a car class

    class Car{
        start(){
            //code
        }
        stop(){
            //code
        }
    }

And you want a Super Car which needs to bounce(but Bounceable feature belongs to ball/rubber)

Here your Super Car can implement bounceable

    public interface Bounceable{

        bounce();
    }

Now you got Super Car car which can bounce.

    class SuperCar extends Car implements Bounceable{
        //My Super Car will bounce.
    }
Jayy
  • 2,368
  • 4
  • 24
  • 35
4

As you have said, interfaces are used to specify contracts which classes that implement them must follow. The scenarios in which they are used is usually a scenario where you call a class which implements a particular interface. The fact that the implements a particular interface provides you with the knowledge that that given class, does indeed implement a given set of methods. Usually you do not care what happens in these methods, what matters to you is that the class has these methods.

As an example, you might want to consider the Observer Design Pattern. Basically, you have one object that has a state which it shares with other objects and passes to them notifications when some of its data changes.

So, if for instance all the observers implement the following interface:

public interface Observer
{
 notify();
}

The Subject can, without any knowledge what so ever about it's observers, do something like this:

public class MySubject...
{
  List<Observer> observers;

  .....



  public void notifyAll()
  {
      for (Observer observer : observers)
      {
         observer.notify();
      }
  }
}

As you can see, the MySubject class does not have any knowledge of how the Observer implements the notify method, what it really cares about is that it implements it. This allows you to create different observers which have different ways of implementing their own notify class without requiring any changes in the MySubject class.

Interfaces also allow for certain type safety. Interfaces are usually also handy when you have a series of classes implementing a series of similar behaviours which you usually want to store into some type-safe data structure. This is usually a good work around the fact that Java does not allow multiple inheritance. So, in the example provided above, I can have an indefinite amount of different classes. But as long as they all implement the Observer interface, they can all be added to the same list.

In the notifyAll methods, then I can just iterate of the elements of the list instead of checking if the element is of a certain type and then casting it, which can introduce some extra overhead in the program's execution.

npinti
  • 51,780
  • 5
  • 72
  • 96
3

It's a classic example but anyway. For example you want to write a game where should be circles, squares, triangles and other shapes. You don't know what shape will come on the next time so you should write an interface with a name say Shape with an abstract method draw and Triangle, Circle, Square classes which are implementing your Shape interface. After that you don't care what shape will come next. You can give to your say drawNext(Shape s) method an instance of Shape and call draw method for that. It will work for all types which are implementing Shape.

public void drawNext(Shape s)
{
     s.draw(); //this will call draw() method of Square if you call drawNext(new Square()) and draw() method of Triangle in case drawNext(new Triangle()) and so on..
}

If you don't use this interface you have to write different method for all types of drowable objects (drawSquare(Square s), drawCircle(Circle c) etc...)

This is one of scopes of interfaces.

shift66
  • 11,760
  • 13
  • 50
  • 83
3

Java does not allow multiple inheritence.

Their design decision was to implement interfaces.

So you can define the desired behavior in an interface and have your class implement it.
This class may extend any other class (only 1) and implement as many interfaces as needed.

Cratylus
  • 52,998
  • 69
  • 209
  • 339
3

The main purpose of interfaces is to act as a guide to programmers who need to implement certain behavior in an implementing class.

For instance, if you were going to implement a Queue class that implements the List interface, the List interface would require that you implement the add method and a remove method, for example.

interface List {

    public void add(Object o);

    public void remove(Object o);

}

If your Queue implements the List interface, you must implement your own version of the add and remove methods. The main advantage of using an interface is that you can then interchange one type with another. For instance:

 // this function returns an ArrayList
 List genericList = (ArrayList) getAnArrayList();  

OR

 // this function returns the Queue you implemented
 List myQueue = (MyQueue) getAQueue(); 

By implementing your class as an interface, you can declare your variables using a more generic type than if you were to use a concrete type. I find this to be really helpful with a bean or data transfer object where one service class might use an ArrayList but another might benefit from using a HashSet. In my bean I can use the interface declaration and let each service class determine what concrete type it wants to use by casting the variable to the concrete type.

Interfaces are basically a way to help standardize things as well as make it easier to swap out one implementing class with another.

I also find that they help me to remember to implement certain methods when I'm programming something, as I can outline them first in the Interface and then the compiler reminds me to implement them.

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • Ok got it. Any other major uses of it ? – Anuj Balan Jan 25 '12 at 08:13
  • As users in other answers mentioned, interfaces can somewhat help with the lack of multiple inheritance. In most cases, they're generally used by library developers or projects where there may be a need to swap out one sub-type with another. Caching or data storage is one possible example. Logging is another. You could use a Datastore interface to abstract your JDO, Hibernate, Postgres, MySQL, etc so you can swap out one with another without needing to change every single variable declaration in your code. – jamesmortensen Jan 25 '12 at 08:23
  • Thank you. I have got my answer. – Anuj Balan Jan 25 '12 at 08:24
3

A class can implement many interfaces and can therefore provide a different "handle" to the class in question. This is how classes are considered to be polymorphic (they can have many forms depending on how you reference them).

Take a look at the java tutorial documentation regarding this. Some useful examples are;

The last link is great in terms of coming to grips with collections in Java and how they utilise interfaces to provide their functionality.

Mr Moose
  • 5,946
  • 7
  • 34
  • 69
2

interfaces are crucial in java because it doesn't have multiple inheritence. If you want your class to be Iterable, but also you want in to implement a certain logic, you cannot inherit from 2 classes, thus you will have to use interface.

So, if you need more then 1 logic to be implemented by a class [which is not uncommon], You cannot use only abstract classes, you'll have to use interfaces

amit
  • 175,853
  • 27
  • 231
  • 333
2

A little history helps:

The object model in java is pretty much a simplified version of the C++ one. That suffered from the "diamond problem" when faced with multiple inheritance.

In java, while 1 class can only ever extend 1 base class, it can implement multiple interfaces. When 2 or more methods in those implemented interfaces have the same signature (name, parameter number and types), the programmer will be consciously aware of that AND in the worst case scenario (in case he forgets to implement methods) their behavior will be defaulted to returning null or doing nothing (that's what IDE's do for you anyway). With multiple inheritance, you'd always have to be aware not to override the methods of the base classes.

This approach to the idea of interfaces works well with the face that all methods in java are by default virtual. This interface construct is thus the way java deals with multiple inheritance and gets some pressure of the programmer.

vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124
2

Yes, an interface consists of abstract methods and final variables, and it is used as a generalized contract put forth so that classes implementing it should implement the methods described.

However, that is not the only use/scope of an interface. That is the definition of an interface.

Interfaces are used where it is know ahead of time that any number of unknown classes might do the job, provided that they all present a standardized set of behaviour. Thus, if I have a Telephone object, and wish to allow someone to listen to it, I might write a Telephone Listener which lays out how a Telephone might signal objects that have not been written yet (and thus have no specific concrete class).

Often in your programming you might provide one (or more) concrete classes; but, an interface is a signal that this is a point of planned extensibility. To go back to my Telephone class example, I might write in the Telephone class.

(assume that listeners is a Collection of TelephoneListener)

public void addListener(TelephoneListener listener) {
  listeners.add(listener);
}

private void simulateCall() {
  for (TelephoneListener listener : listeners) {
    listener.onRing();
  }
}

signalling TelephoneListeners which haven't even been written (yet) that a telephone rang.

It's not really "just" about simulating multiple inheritance, although those coming from a C++ background identify it as a means of "solving" multiple inheritance. It's about specifying a contract for future classes to implement. C++'s multiple inheritance confuses contract with implementation (and thus you run the risk of the dreaded diamond pattern).

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
0

A broad example is :
Java Language Specification[interface,contract] from Java community
Implementation by different vendors like Sun/Oracle JDk, IBM JDK, OpenJDK etc

lowLatency
  • 5,534
  • 12
  • 44
  • 70