6

I have two programs one implemented using interfaces and the other implemented using only classes - I've read that the advantage of using an interface is that it can provide it's own implementation of methods of super class but that can be done using abstract classes or method overriding. What purpose does interfaces serve?
In what kind of hierarchy and situation using interface will be most beneficial?

INTERFACE

interface Shape
{
    void area(int x, int y);
}
class Rectangle implements Shape
{
    @Override
    public void area(int length, int breadth)
    {
        System.out.println(length*breadth);
    }
}
class Triangle implements Shape
{
    @Override
    public void area(int base, int height)
    {
        System.out.println(base*height);
    }
}
public class ShapeUsingInterface
{
    public static void main(String X[])
    {
        Rectangle r = new Rectangle();
        Triangle t  = new Triangle();

        r.area(5, 4);
        t.area(6, 3);
    }
}


CLASS

class Shape
{
    void Area(int x, int y)
    {
        System.out.println(x*y);
    }
}
class Rectangle extends Shape
{

}
class Triangle extends Shape
{
    @Override
    void Area(int base, int height)
    {
        System.out.println((0.5)*base*height);
    }
}
public class CalculateArea 
{
    public static void main(String X[])
    {
        Rectangle r = new Rectangle();
        Triangle t = new Triangle();

        r.Area(4, 5);
        t.Area(6, 8);
    }
}
Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • 6
    You can implement multiple interfaces but only extend a single class – Philippe Jan 05 '15 at 10:32
  • 2
    Well, the important difference is, *an interface defines an unbreakable contract*. So it makes the classes that implement it to *explicitly* implement the method. A class on the other hand doesn't explicitly expect you to implement the methods. – TheLostMind Jan 05 '15 at 10:38

4 Answers4

11

To explain why interfaces are used, you have to first understand a problem with inheritance. It's called the Diamond Problem. Simply, if a class, D inherits from two classes B and C, and B and C both inherit from the same class A, which implementation of the methods from A does D get?

enter image description here

What we're left with is a method ambiguity that Java does not like! So the way of preventing this is to make sure that D can only ever have one superclass, so it could inherit from either A, B or C, but never more than one. So that prevents the problem, but we lose all of the perks that multiple inheritance offers!

Enter the Interface. This allows us to have the perks of multiple inheritance (referencing the single class as various different types) and still avoid the diamond problem, because the implementing class provides the method. This removes the method ambiguity.

This means that, for example:

public abstract class MyClass {
    public void doSomething();
}

public class MyConcreteClass extends MyClass {
    public void doSomething() {
        // do something
    }
}

You can either refer to an instance of MyConcreteClass as

 MyClass class = new MyConcreteClass();

or

 MyConcreteClass class = new MyConcreteClass();

But never anything else, given this implementation. You can't extend more classes because you'll potentially get the diamond problem, but you CAN include an Interface

public class MyConcreteClass extends MyClass implements Serializable {
}

All of a sudden, you can say..

Seralizable myClass = new MyConcreteClass();

Because myClass is a Serializable. This is excellent for decoupling classes from one another, when a method might not need to know that it is an instance of MyConcreteClass, only that it has a necessary subset of methods.

In short: You can implement many interfaces, but you can only inherit one class.

christopher
  • 26,815
  • 5
  • 55
  • 89
  • Good answer. I would also like to see in your answer that you could implement multiple interfaces but can only extend one class as a line somewhere in this answer. I expected to read this, but didn't see that directly. – Joop Jan 05 '15 at 10:56
  • 1
    @Joop Added for you. – christopher Jan 05 '15 at 14:10
2

Interface defines the contract. Say for example:

interface MusicPlayer
{
  public void shuffle();
}

Now each class implementing the interface can have their own algorithm for implementing shuffle method, its upto them. Abstract class is similar to interface, where an abstract class defines few methods to be common and leave other methods to be implemented in our own way. Like

abstract class MusicPlayer
{
  public void turnOff()
  {
     //kill the app
  }

  abstract public void shuffle();
}

And using interfaces you can implement multiple interfaces but only extend a single class.

Ant's
  • 13,545
  • 27
  • 98
  • 148
2

You can see interfaces as a social contract which states that all the classes who implement the interface should define the methods declared in the interface. This creates continuity between all the classes which implement them, and that's awesome if you want all those classes to have the same behaviors. Since an interface does not declare the implementation itself, it leaves that to the class that implements it. This way you create for example many machines which all have a start button, something you would likely want them all to have. Better said required them all to have, the social contract makes sure this is the case since you must implement every method of an interface! That is required by the compiler.

A class which overrides all the methods in of an other class (by extending the class and implementing in on its one) does not truly say that it will always truly keep this promise. The benefit of knowing that the class will be loyal is gone and you obscure the logic behind it. It would be less clear to see if all methods are overridden or not, and that's bad practice. Why not make your logic clear and actually implement the social contract with an interface.

Abstract classes are a little bit different in that they also implement methods, as seen by normal classes, and also work as an interface because they also require that you implement declared but unimplemented methods. In java 8 interfaces can do this too.

Joop
  • 3,706
  • 34
  • 55
  • 2
    This answer is not fully true anymore for java8 due to the default implementation. In Java 8 interfaces may contain also certain method implementations. – mschenk74 Jan 05 '15 at 10:50
2

I would say that in your example Shape should definitely not be class, but interface. You have provided default implementation for area calculation as x*y, hovewer in case of most shapes this implementation is not correct.

If you will add new shape you will inherit method with incorrect implementation. You will have to remember to check all methods in all classes to validate inherited methods. In case of interface you can't make this mistake.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63