Java extends vs. implements

In Java, the extends keyword is used for extending a class or interface; and the implements keyword is used for implementing the interfaces into a class. It is the main difference between extends and implements.

Note that extends and implements are reserved keywords in Java and cannot be used as identifiers.

1. Java extends

In Java, we can inherit the fields and methods of a class by extending it using extends keyword. Please note that a Java class is allowed to extend one and only one class. Java does not support multiple inheritance to avoid the diamond problem.

public class Child extends Parent {

    //...
}

An interface can extend another interface using the extends keyword when used with interfaces.

public interface IChild extends IParent {

    //...
}

Take the example of ArrayList class. It extends AbstractList class which in turn extends AbstractCollection class. So essentially ArrayList class has methods and behaviors of both parent classes.

2. Java implements

In Java, interfaces are ways to enforce a contract onto classes. Interfaces force the implementing classes to implement a certain behavior. To implement an interface, a class must use implements keyword.

public class WorkerThread implements Runnable {

    //...
}

In Java, we can implement more than one interface. In this case, the class must implement all the methods from all the interfaces. (or declare itself abstract).

For example, the ArrayList class implements four interfaces i.e. List, RandomAccess, Cloneable and Serializable. It has implemented all the methods from these interfaces.

3. Differences between extends and implements

Based on the above examples, let’s list down the differences between extends and implements keywords in Java.

  • extends keyword is used to inherit a class or interface, while implements keyword is used to implement the interfaces.
  • A class can extend only one class but can implement any number of interfaces.
  • A subclass that extends a superclass may override some of the methods from superclass. A class must implement all the methods from interfaces.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode