Implements vs extends: When to use? What's the difference?

1,225,893

Solution 1

extends is for extending a class.

implements is for implementing an interface

The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
     public void doAction() {
       //specify what must happen
     }

     public String doThis(int number) {
       //specfiy what must happen
     }
 }

now extending a class

 public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

in this case

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2

Also, note that an @Override tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden

I suggest you do some more research on dynamic binding, polymorphism and in general inheritance in Object-oriented programming

Solution 2

I notice you have some C++ questions in your profile. If you understand the concept of multiple-inheritance from C++ (referring to classes that inherit characteristics from more than one other class), Java does not allow this, but it does have keyword interface, which is sort of like a pure virtual class in C++. As mentioned by lots of people, you extend a class (and you can only extend from one), and you implement an interface -- but your class can implement as many interfaces as you like.

Ie, these keywords and the rules governing their use delineate the possibilities for multiple-inheritance in Java (you can only have one super class, but you can implement multiple interfaces).

Solution 3

Generally implements used for implementing an interface and extends used for extension of base class behaviour or abstract class.

extends: A derived class can extend a base class. You may redefine the behaviour of an established relation. Derived class "is a" base class type

implements: You are implementing a contract. The class implementing the interface "has a" capability.

With java 8 release, interface can have default methods in interface, which provides implementation in interface itself.

Refer to this question for when to use each of them:

Interface vs Abstract Class (general OO)

Example to understand things.

public class ExtendsAndImplementsDemo{
    public static void main(String args[]){

        Dog dog = new Dog("Tiger",16);
        Cat cat = new Cat("July",20);

        System.out.println("Dog:"+dog);
        System.out.println("Cat:"+cat);

        dog.remember();
        dog.protectOwner();
        Learn dl = dog;
        dl.learn();

        cat.remember();
        cat.protectOwner();

        Climb c = cat;
        c.climb();

        Man man = new Man("Ravindra",40);
        System.out.println(man);

        Climb cm = man;
        cm.climb();
        Think t = man;
        t.think();
        Learn l = man;
        l.learn();
        Apply a = man;
        a.apply();

    }
}

abstract class Animal{
    String name;
    int lifeExpentency;
    public Animal(String name,int lifeExpentency ){
        this.name = name;
        this.lifeExpentency=lifeExpentency;
    }
    public void remember(){
        System.out.println("Define your own remember");
    }
    public void protectOwner(){
        System.out.println("Define your own protectOwner");
    }

    public String toString(){
        return this.getClass().getSimpleName()+":"+name+":"+lifeExpentency;
    }
}
class Dog extends Animal implements Learn{

    public Dog(String name,int age){
        super(name,age);
    }
    public void remember(){
        System.out.println(this.getClass().getSimpleName()+" can remember for 5 minutes");
    }
    public void protectOwner(){
        System.out.println(this.getClass().getSimpleName()+ " will protect owner");
    }
    public void learn(){
        System.out.println(this.getClass().getSimpleName()+ " can learn:");
    }
}
class Cat extends Animal implements Climb {
    public Cat(String name,int age){
        super(name,age);
    }
    public void remember(){
        System.out.println(this.getClass().getSimpleName() + " can remember for 16 hours");
    }
    public void protectOwner(){
        System.out.println(this.getClass().getSimpleName()+ " won't protect owner");
    }
    public void climb(){
        System.out.println(this.getClass().getSimpleName()+ " can climb");
    }
}
interface Climb{
    public void climb();
}
interface Think {
    public void think();
}

interface Learn {
    public void learn();
}
interface Apply{
    public void apply();
}

class Man implements Think,Learn,Apply,Climb{
    String name;
    int age;

    public Man(String name,int age){
        this.name = name;
        this.age = age;
    }
    public void think(){
        System.out.println("I can think:"+this.getClass().getSimpleName());
    }
    public void learn(){
        System.out.println("I can learn:"+this.getClass().getSimpleName());
    }
    public void apply(){
        System.out.println("I can apply:"+this.getClass().getSimpleName());
    }
    public void climb(){
        System.out.println("I can climb:"+this.getClass().getSimpleName());
    }
    public String toString(){
        return "Man :"+name+":Age:"+age;
    }
}

output:

Dog:Dog:Tiger:16
Cat:Cat:July:20
Dog can remember for 5 minutes
Dog will protect owner
Dog can learn:
Cat can remember for 16 hours
Cat won't protect owner
Cat can climb
Man :Ravindra:Age:40
I can climb:Man
I can think:Man
I can learn:Man
I can apply:Man

Important points to understand:

  1. Dog and Cat are animals and they extended remember() and protectOwner() by sharing name,lifeExpentency from Animal
  2. Cat can climb() but Dog does not. Dog can think() but Cat does not. These specific capabilities are added to Cat and Dog by implementing that capability.
  3. Man is not an animal but he can Think,Learn,Apply,Climb

By going through these examples, you can understand that

Unrelated classes can have capabilities through interface but related classes override behaviour through extension of base classes.

Solution 4

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. enter image description here

For more details

Solution 5

extends is for when you're inheriting from a base class (i.e. extending its functionality).

implements is for when you're implementing an interface.

Here is a good place to start: Interfaces and Inheritance.

Share:
1,225,893
Saad Masood
Author by

Saad Masood

Full Stack Developer

Updated on September 06, 2021

Comments

  • Saad Masood
    Saad Masood almost 3 years

    Please explain in an easy to understand language or a link to some article.

  • Mark Peters
    Mark Peters about 12 years
    And extends is also for when you're extending an interface :-).
  • Philipp Reichart
    Philipp Reichart about 12 years
    An interface can contain way more than method declarations: Constant fields, annotations, interfaces and even classes.
  • user2492854
    user2492854 over 10 years
    are they something like modules and mixins in ruby?
  • João dos Reis
    João dos Reis almost 10 years
    @user2492854 a little bit, but there won't be any implemented methods in an interface. It's literally a description of an interface, not an implementation.
  • ADTC
    ADTC over 9 years
    A new feature in Java 8 allows implementation of default behavior for methods in interfaces, making the custom implementation of those methods optional. Therefore the statement "you can only specify methods, but not implement them" is only fully correct for Java 7 and below.
  • weiheng
    weiheng over 7 years
    "extends is for extending a class", is a little bit confusing. Sine an interface and extends an interface too . For example: public interface ListIterator<E> extends Iterator<E>
  • MatthewRock
    MatthewRock over 7 years
    Is that really so? I always thought "has a" refers to having something, possessing it. You could say that cat "has a" climbing ability, but I would say reword your example. Cat "is a" Climber", man "is a" "thinker, learner, climber". Since man "is a" thinker, he can do what a thinker can do. It is even clearer when working with some protocols - if you have a house, it has a door, but it doesn't implement pushingHandle. It also "is a" MaterialObject, meaning it implements interface for obeying gravity; it doesn't have a "GravityObeyingSkill" or something similar.
  • Ravindra babu
    Ravindra babu over 7 years
    If Man is a thinker, I will establish relation with extends and not implements. Thinker may have some state and other roles/features but I will implement thinking capability only with interface. IS A is standard term used for inheritance.
  • blinking-in-the-light
    blinking-in-the-light over 7 years
    Thanks for making the distinction that Oracle's own tutorial forgot to; that you make either a class or an interface, not both. I was banging my head against a wall wondering why I couldn't make an interface for my class.
  • max
    max about 7 years
    Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces: how so? The lack of multiple inheritance of classes means that you cannot combine implementation from multiple sources, and I don't think multiple interfaces change that in any way?
  • Maggyero
    Maggyero over 3 years
    If the figures used the correct UML notations (hollow triangles) this answer would be perfect.
  • notacorn
    notacorn over 3 years
    extends is for extending classes or interfaces