Tuesday, September 7, 2021

Difference between extends and implements keywords in Java? Example Tutorial

Though both extends and implements keyword in Java is used to implement Inheritance concept of Object-Oriented programming, there is a subtle difference between them. The extends keyword is mainly used to extend a class i.e. to create a subclass in Java, while the implements keyword is used to implement an interface in Java. The extends keyword can also be used by an interface for extending another interface. In order to better understand the difference between extends and implements, you also need to learn and understand the difference between class and interface in Java.

Though both are an integral part of application development using the object-oriented methodology, an interface is more abstract than a class hence it is used to define API or contract.

On the other hand, a class provides the concrete implementation of the interface i.e. the actual code which does the job. Though a class can also be abstract to define a contract, it's the job best done by an interface in Java. 

Even Joshua Bloch has advised in Effective Java about user interfaces to declare Type in Java, as it promotes multiple inheritances in Java, which is restricted as compared to C++.

Even after Java 8, only multiple inheritances of type and behavior are supported in Java (by introducing default methods in Java 8), but multiple inheritances of the state are still not supported. If you want to learn more about why multiple inheritances are not supported in Java, see here.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

What is the meaning of extending a class?

A class in Java can extend to another class to become a subclass. When class B extends class A, B becomes subclass (child) and A becomes superclass (parent). A subclass can reuse all the features of the parent class and code reuse is a major reason for extending a class but few understand that more important is the defining relationship which is later leveraged by Polymorphism.

For example, if class B extends class A then a reference variable of type A can hold the object of B, which means A now becomes polymorphic because it can hold both A and B. This gives birth to a technique of creating flexible software, known as programming for interface than implementation where you always use variables of the parent class or interface to define the core algorithm.

The benefit of doing this is any new class that extends the parent class will have access to that algorithm.


Here is an example of extending a class in Java:

class A {
  public void show() {
    System.out.println("show");
  }
}

class B extends A {
  public void display() {
    System.out.println("display");
  }

  public void show() {
    System.out.println("better show");
  }
}

public class Main {

  public static void main(String[] args) {

    A a = new B(); // possible because B extends A
    a.show(); // this will now call to show() method of class B
  }
}

Output
better show

You can see that by extending class A, B now has access to the show() method, it can even override the behavior of the show() method, which is known as method overriding in Java. This immense power comes by using the extends keyword.

You can also read the Head First Design Pattern in Java to learn more about the technique of programming for interface than implementation. The book is also recently updated to cover Java SE 8.

Difference between extends and implements keywords in Java



What is the meaning of implementing an interface

The meaning of implementing an interface is not very different than extending a class but it comes with an additional caveat. When a class implements an interface it has to provide an implementation of all methods declared inside the interface. If It doesn't wish to provide all implementation, it can declare itself as an abstract class.

Not following these rules means your program cannot compile. There are many examples of implementing an interface in Java code, but I believe implementing Runnable is the most popular. This is used to create a Runnable task that can be executed by a thread.

class R implements Runnable{
public void run(){
   System.out.println("do nothing");
  }
}

An instance of R now can be passed to any method which expects a Runnable like you can pass this to both execute() and submit() method of ExecutorService class to run that task in a thread pool. Since our class has implemented the run() method, the single method from interface Runnable, it is a concrete class. If it had not implemented the run() method you have to make it abstract by adding the abstract keyword in front of the class like:

abstract class R implements Runnable{

}

Difference between extends and implements keywords in Java


Important points

Here are some of the important points related to extends and implements keywords in Java:

1) A class can only extend another class in Java, use extends keyword with the interface will result in a compilation error as shown below:

interface I{

}

class A{
}

class B extends A{

}

class C extends I{

}

When you compile this source file you will get the following error:

$ javac Main.java
Main.java:27: no interface expected here
class C extends I{
^
1 error


2) A class can only extend one class, trying to extend more than class will again result in a compilation error as shown below:

class C extends A, B{

}

$ javac Main.java
Main.java:27: '{' expected
class C extends A, B{
^
1 error


3) An interface can use extends keyword to create subinterfaces in Java e.g. following is perfectly legal in Java

interface J extends I{

}


4) An interface can even extend multiple interfaces by using extends keyword as shown below:

interface k extends I, J{

}


5) A class can use the implements keyword to implement one or more interfaces in Java as shown below:

class D implements I, J, K{

}


6) A class can also use both extends and implements keywords together to extend a class and implement an interface, it's quite common in Java as shown in the following example:

class E extends A implements I, J{

}

When a class does that it is now a subclass of A and subinterface of I and J, which means you can use a reference variable of class E and interface I, J to store class E object as shown below:

I i = new E();
J j = new E();
A a = new E();

This gives immense power to class E in terms of using Inheritance and Polymorphism.


7) Last but not least, an interface cannot use implements keyword to implement an interface, it's illegal in Java and the compiler will throw an error as shown below:

interface L implements J{

}

javac Main.java
Main.java:49: '{' expected
interface L implements J{
^
1 error


That's all about the difference between extends and implements keywords in Java. It's clear that extends is generally used to extend a class and implements are generally used to implement an interface. Though there are more subtleties e.g. an interface can also extend another interface to become a subinterface, a class can also be abstract even after implementing an interface but what doesn't change is that they both are used to create the parent-child relationship in Java.

If class B extends another class A it becomes its children and class A becomes a parent. The same is true with the interface. You can further read Head First Java and Head First Object-Oriented Analysis to learn more about the basic building blocks of Object-Oriented programming in java.


Other Java Interview Questions you may like
  • Difference between Aggregation, Association, and Composition in Java? (answer)
  • Why Composition is better than Inheritance in Java? (article)
  • Difference between the static and non-static variables in Java? (answer)
  • Why abstract class is important in Java? (opinion)
  • 5 Free Courses to learn Object Oriented Programming (courses)
  • Difference between Factory and Dependency Injection Pattern? (answer)
  • How to create thread-safe Singleton in Java (example)
  • Difference between Abstract class and Interface in Java? (answer)
  • How to implement the Strategy Design Pattern in Java? (example)
  • Difference between Factory and AbstractFactory Pattern? (example)
  • 18 Java Design Pattern Interview Questions with Answers (list)
  • Difference between Inheritance and Polymorphism in Java? (answer)
  • How to design a Vending Machine in Java? (questions)
  • Difference between Abstraction and Polymorphism in Java? (answer)
  • 20 System Design Interview Questions (list)
  • Difference between State and Strategy Design Pattern in Java? (answer)

Thanks for reading this article, if you have any doubt or question, post a comment and if you like the article, don't forget to share with your friends. 

3 comments :

Unknown said...

extends is for extending a class.

implements is for implementing an interface

javin paul said...

Well Ashok, you can also use extends to extend an interface e.g. interface A extends interface B

Unknown said...

Hi Javin,
why extend keyword used before the implements keyword in Java?

Post a Comment