25

Let's say you have an interface

public interface Change {

    void updateUser();
    void deleteUser();
    void helpUser();

}

I've read that interfaces are Java's way to implement multiple inheritance. You implement an interface, then you have access to its methods. What I don't understand is, the methods don't have any body in the interface, so you need to give them a body in your class. So if you an interface is implemented by more than one class, you need to give the method a body in more than one class. Why is this better than just having individual methods in your classes, and not implementing an interface?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Killian
  • 936
  • 3
  • 14
  • 28
  • 3
    [Polymorphism](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) – Brian Jul 16 '13 at 20:11
  • 1
    you will find Interface useful when you starts for designing a library and its API buddy :) –  Jul 16 '13 at 20:11
  • @Brian, polymorphism is not a complete answer since this behavior can already be generated by subclassing. – Stefan Falk Jul 16 '13 at 20:18
  • A little google search would lead you to a lot of answers. [Read the comment of Michael Borgwardt](http://stackoverflow.com/questions/504904/how-are-java-interfaces-actually-used) but anyway.. I have the same problem like you and I personally don't see the real benefit from interfaces.. – Stefan Falk Jul 16 '13 at 20:17
  • @NathanHughes That question pertains to php. (Actually, I suppose it speaks about interfaces more generally, but I still wouldn't mark this as a duplicate of that question). – arshajii Jul 16 '13 at 20:29
  • 1
    @arshajii: agreed, I retracted the close vote. – Nathan Hughes Jul 16 '13 at 20:45
  • 2
    It's better _in many situations_ because each implementation could be **completely** different. I love how [this answer](http://stackoverflow.com/a/384067/778118) gets the point across. Using an interface is far more powerful than implementing one method in multiple classes, because if each class implements the same interface, you can treat them all the same (without casting). Here's [another answer](http://stackoverflow.com/a/12684564/778118) that shows some ways you can take advantage of using interfaces. – jahroy Jul 16 '13 at 20:53

6 Answers6

64

My professor in college once gave a great anecdote to describe polymorphism and encapsulation. It went like this.


Does anyone here know how a soda machine works? (Cue confused glances about why we'd even talk about this.) No? Let me tell you.

You drop in your change, and inside the machine is a little monkey who counts all your change to make sure you put in enough money. When you press the button for your soda, a little light comes on telling the monkey which button you pressed, and if you entered the right amount of change, he grabs your choice and throws it into the little hole for you to grab your soda.

This is the concept of encapsulation. We hide the implementation of the soda machine. Unless it's got one of those fancy, clear windows to let you see the inside, you honestly have no idea how it really works. All you know is that you put in some cash, you press a button, and if you put in enough, you get your drink.

To add to that, you know how to use a soda machine's interface, so therefore as long as the machine's interface follows the usual soda machine interface, you can use it. This is called the interface contract. The machine can be bringing the drinks from Antarctica on a conveyor belt for all you care, as long as you get your drink, it's cold, and you get change back.

Polymorphism is the idea that when you use the soda machine interface, it could be doing different things. This is why encapsulation and polymorphism are closely related. In polymorphism, all you know is that you're using a SodaMachine implementation, which can be changed, and as a result, different things can be done behind the scenes. This leads to the driving concept of polymorphism, which is the ability of one object, the SodaMachine, to actually act as both a MonkeySodaMachine and a ConveyorSodaMachine depending on the machine actually behind the interface.


Probably not word-for-word, but close enough. Essentially it boils down to two concepts: polymorphism and encapsulation. Let me know if you want clarification.

Brian
  • 17,079
  • 6
  • 43
  • 66
  • 7
    Very nice analogy. One powerful thing interfaces let you do is order a truck full of soda machines that all work differently and put them all in the same list. – jahroy Jul 16 '13 at 20:59
  • it could have been a better analogy if there were more than one monkeys for each different type of drink as xMonkey.java , yMonkey.java. – ralzaul Feb 19 '15 at 11:56
  • 1
    I feel like this soda machine example is more related to abstraction. IMO idk – Charitha Goonewardena Jun 09 '17 at 09:09
  • 1
    @CharithaGoonewardena Abstraction, polymorphism, and encapsulation are, in a practical sense, all linked together. If you take an implementation and *encapsulate* it, then add a layer of *abstraction*, you can achieve *polymorphism*. Put another way, you can't have abstraction without encapsulation, and you can't have polymorphism without abstraction. Adding a layer of abstraction is what enables polymorphism. – Brian Jun 09 '17 at 13:54
  • @Brian. Got it. Thanks for the information. – Charitha Goonewardena Jun 10 '17 at 09:59
14

Why is this better than just having individual methods in your classes, and not implementing an interface?

Because if a class C implements an interface I, you can use a C whenever an I is expected. If you do not implement the interface, you could not do this (even if you provided all of the appropriate methods as mandated by the interface):

interface I {
    void foo();
}

class C1 implements I {
    public void foo() {
        System.out.println("C1");
    }
}

class C2 {  // C2 has a 'foo' method, but does not implement I
    public void foo() {
        System.out.println("C2");
    }
}

...

class Test {
    public static void main(String[] args) {
        I eye1 = new C1();  // works
        I eye2 = new C2();  // error!
    }
}
arshajii
  • 127,459
  • 24
  • 238
  • 287
10

It separates what the caller expects from the implementation. You have a pure set of methods you can call without any knowledge of the implementation. In fact some libraries like JMS and JDBC provide interfaces without any implementations.

This separation means you don't need to know the class of any actual implementation.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

An interface allows you to guarantee that certain methods exist and return the required types. When the compiler knows this, it can use that assumption to work with unknown classes as if they had certain known behavior. For example, the comparable interface guarantees that an implementing class will be able to compareTo() some similar object and will return an int.

This means that you can compare anything that implements this interface - so you can sort anything that is Comparable instead of writing one method to sort Strings and another to sort Integers and another to sort LabelledBoxesOfBooks

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
2

The interface essentially guarentees that all the methods that inherit it will have its methods, so that you can safely call a method in the interface for anything that inherits it.

StephenTG
  • 2,579
  • 6
  • 26
  • 36
0

It makes it easier to define APIs using interfaces, so that all concrete implementations of the interfaces provide the expected methods in each class.

It also provides a way to implement multiple inheritance, which is not possible (in Java) with straight class inheritance.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52