Sunday, September 24, 2023

Difference between Class and Interface in Java and OOP? (with Example)

It is one of the frequently asked Java questions from beginners who struggle 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 a method name but how the behavior of that method has 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 languages, 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 vs interface in Java and OOP

Now, let's examine both syntactical and functional differences 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 that implements a 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 these free Java 8 tutorials 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 allows multiple inheritances in form of one interface extending multiple interfaces but doesn't allow C++ style multiple inheritances where a class can extend multiple classes.

5. Flexibility

The interface adds flexibility to coding. Any code which is written using an interface is 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 also see my post on 10 object-oriented design principles which every Java developer should know to learn more about that.

6. UML Diagram

In the UML diagram, an interface is represented using keyword <<interface>> while the class doesn't need any words. Any class which implements an interface is also denoted via a dotted line with an arrowhead as shown in the following diagram. 

In the below diagram, you have a class called Circle which implements an interface called GeometricObject. There is another class called ResizableCircle which extends the Circle class and implements another interface called Resizable

If you are not very familiar with UML then 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 like Stock, Future, Option will be the classes which implement Instruments.

Any code, which needs an Instrument like Order needs 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 the interface.

That's all about the difference between a class and an 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 the 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 answers (list)
  • Why abstract class is important in Java? (answer)
  • 21 Java Inheritance Interview Questions with Answers (list)
  • Difference between abstraction and polymorphism in Java? (answer)
  • Can we declare a constructor inside the abstract class in Java? (answer)

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

And lastly one question for you? What is SOLID design principle in Object oriented programming? Can you name all the 5 object oriented principle which are part of SOLID? 

1 comment:

  1. The key difference between an interface and a class is that what define contract and other implement it. From JDK 8 onwards, difference between a class and an interface has gone down in Java as now you can also have static and default methods inside interface which can contain concrete things rather then just specify what to do.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.