What is the difference between extends and implements in Java?

In Java, extends and implements are both keywords used to achieve inheritance, but they are used in different contexts and have distinct purposes.

extends Keyword:

  • Purpose: The extends keyword is used for class inheritance. It allows a class to inherit from another class or an abstract class.
  • Single Inheritance: A class can only extend one class (single inheritance).
  • Usage: When a class extends another class, it inherits the fields and methods of the parent class.
  • Example: Extending a class or abstract class.

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}
class Dog extends Animal {  

void bark() {

System.out.println("The dog barks.");

}

}

public class Main {

public static void main(String args) {

Dog dog = new Dog();

dog.eat(); // Inherited from Animal

dog.bark(); // Defined in Dog

}

}

  • In this example: Dog class extends Animal, inheriting its behavior.

implements Keyword:

  • Purpose: The implements keyword is used for interface inheritance. It allows a class to implement one or more interfaces.
  • Multiple Inheritance: A class can implement multiple interfaces, achieving a form of multiple inheritance.
  • Usage: When a class implements an interface, it must provide implementations for all the abstract methods declared in the interface.
  • Example: Implementing interfaces.

Example:

interface Animal {
    void eat();
}
interface Bird {  

void fly();

}

class Bat implements Animal, Bird {

public void eat() {

System.out.println("The bat eats insects.");

}

public void fly() {
System.out.println("The bat flies.");
}


}

public class Main {

public static void main(String args) {

Bat bat = new Bat();

bat.eat(); // Implements Animal interface

bat.fly(); // Implements Bird interface

}

}

  • In this example: Bat class implements both Animal and Bird interfaces and provides implementations for their methods.

Key Differences:

\| Aspect \| extends \| implements \|

\|---------------------\|---------------------------------------------------\|---------------------------------------------------\|

\| Used for \| Extending a class (or abstract class) \| Implementing an interface \|

\| Type of Inheritance \| Single inheritance (class can extend only one class) \| Multiple inheritance (class can implement multiple interfaces) \|

\| Method Implementation \| Can inherit methods, and override if needed. \| Must provide implementations for all interface methods. \|

\| Keyword \| Used with classes or abstract classes \| Used with interfaces \|

\| Example \| class Dog extends Animal {} \| class Bat implements Animal, Bird {} \|

Summary:

  • extends is used for class inheritance (single inheritance).
  • implements is used for interface inheritance (multiple inheritance).