Difference between a class and an interface in Java

It is one of the frequently asked Java questions from beginners which struggles to get the concept behind an interface. The main difference between a class and an interface lies in their usage and capabilities. An interface is the purest form of abstraction available in Java where you just define the API or contract e.g. you define run() method on the Runnable interface without worrying about how something will run, that is left to the implementor which will use a class to define how exactly to run. So an interface gives you method name but how the behavior of that method is come from the class which implements it. That's your general difference between an interface and class in Java and applicable to all object oriented programming language, not just Java. Even though this question is not exactly the difference between abstract class and interface, it's somewhat related to it because an abstract class is nothing but a class with some abstract method. The points I have discussed there, also applicable here in terms of rules of Java programming related to class and interface.



Difference between class and interface in Java

Now, let's examine both syntactical and functional difference between a class and interface in Java point by point, this will give you a better idea of both of them.

1) Purpose
The interface is best suited for defining type because it promotes multiple inheritances in Java. It is even recommended by Joshua Bloch in Effective Java. Since an interface can extend multiple interfaces and a class can implement multiple interfaces, it suddenly becomes more polymorphic. On the other hand, a class is best suited for writing concrete code which does the actual job.



2) Instantiation
Since an interface is completely abstract you cannot create an object of them but a class can be both abstract and concrete hence you can create an object of a concrete class in Java.

For example
Runnable r = new Runnable(); // compiler error 
but
Runnable r = new Task();; // Ok

where Task is a class which implements Runnable interface.


3) State
An interface can define constants but that is not part of the state of an object, which is only defined by the instance variable. You cannot define state variable inside interface in Java until JDK 7 but that is changed now in Java SE 8, where you can define both static and default methods inside interface. (see Java SE 8 for Really Impatient by Cay S. Horstmann to learn more about static and default methods)


4) Inheritance
A class can only inherit one class but an interface can extend multiple interfaces. Similarly, a class can implement multiple interfaces but an interface cannot extend a class. This might seem confusing to you but Java allow multiple inheritance in form of one interface extending multiple interface but doesn't allow C++ style multiple inheritance where a class can extend multiple classes.


5) Flexibility
Interface adds flexibility in coding. Any code which is written using interface are more adaptable to a change than code written using concrete classes. This is also a popular object oriented design principle, commonly known as "programming for interfaces than implementation". You can see my post 10 object oriented design principles which every Java developer should know to learn more about that.


6) UML Diagram
In UML diagram an interface is represented using keyword <<interface>> while class doesn't need anyword. Any class which impelments interface is also denoted via dotted line with arrowhead as shown in following diagram. In this diagram you have a class called Circle which implements an interface called GeometricObject. There is another class called ResizableCircle which extends Circle class and implement another interface called Resizable. If you are not very familiar with UML than you should read UML for Java Programmers by Uncle Bob to learn more about UML in Java)

Difference between a class and interface in Java



When to use a class and interface in Java?

This is the most important question you should ask, this is even more important than the difference between class and interface but both are related to each other. If a candidate understands the class and interface concept correctly he can answer both of these questions. If you are writing a trading application, you can define an Instrument interface and all type of instrument e.g. Stock, Future, Option will be the classes which implement Instruments. Any code, which needs an Instrument e.g. Order need an Instrument then you can code with Instrument and it will work for any Instrument including Stock, Future, and Options as shown below:

public class ClassVsInterface {

  public static void main(String[] args) {

    Instrument[] instruments = new Instrument[3];
    instruments[0] = new Stock();
    instruments[1] = new Future();
    instruments[2] = new Option();

    for (Instrument i : instruments) {
      print(i);
    }

  }

  public static void print(Instrument instrument) {
    System.out.println(instrument.getAssetClass());
  }
}

interface Instrument {
  public String getAssetClass();
}

class Stock implements Instrument {

  @Override
  public String getAssetClass() {
    return "STOCK";
  }

}

class Future implements Instrument {

  @Override
  public String getAssetClass() {
    return "FUTURES";
  }

}

class Option implements Instrument {
  @Override
  public String getAssetClass() {
    return "OPTION";
  }
}

You can see that since we have defined Instrument as interface the print() method can work with Stock, Future, and Option, that's the power of Inheritance and Polymorphism which comes by using interface.

That's all about the difference between a class and interface in Java. The most important difference is to understand when to use a class and interface. As I have previously explained on actual use of interface in Java, it let you write polymorphic code which adds flexibility to your software. This is also known as "programming for interfaces" in the object-oriented world.

Related Java and OOP tutorials you may like:
  • Difference between abstraction and encapsulation in Java? (answer)
  • 30 OOP questions from Java Interviews with answrs (list)
  • Why abstract class is important in Java? (answer)
  • 21 Java Inheritance Interview Questions with answers (list)
  • Differnece between abstraction and polymorphism in Java? (answer)
  • Can we declare constructor inside abstract class in Java? (answer)


References
The Java Language Specification (Java SE 8)
Class in Object Oriented Programming (Wikipedia)



No comments:

Post a Comment