763
votes

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

19
link This example made some understanding easily about the Interface and abstract class ie implements and extends in java.User Learning
extends is an element of the extension spaceJobHunter69

19 Answers

790
votes

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

82
votes

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).

60
votes

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.

42
votes

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.

34
votes

A class can only "implement" an interface. A class only "extends" a class. Likewise, an interface can extend another interface.

A class can only extend one other class. A class can implement several interfaces.

If instead you are more interested in knowing when to use abstract classes and interfaces, refer to this thread: Interface vs Abstract Class (general OO)

34
votes

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

31
votes

An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X". Again, as an example, anything that "ACTS LIKE" a light, should have a turn_on() method and a turn_off() method. The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.

An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a scooter class and a truck class. Each of these three classes should have a start_engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start_engine action is the domain of the interface.

19
votes

Extends : This is used to get attributes of a parent class into base class and may contain already defined methods that can be overridden in the child class.

Implements : This is used to implement an interface (parent class with functions signatures only but not their definitions) by defining it in the child class.

There is one special condition: "What if I want a new Interface to be the child of an existing interface?". In the above condition, the child interface extends the parent interface.

17
votes

Both keywords are used when creating your own new class in the Java language.

Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.

Refer to oracle documentation page on interface for more details.

This can help to clarify what an interface is, and the conventions around using them.

15
votes
  • A extends B:

    A and B are both classes or both interfaces

  • A implements B

    A is a class and B is an interface

  • The remaining case where A is an interface and B is a class is not legal in Java.

12
votes

Implements is used for Interfaces and extends is used to extend a class.

To make it more clearer in easier terms,an interface is like it sound - an interface - a model, that you need to apply,follow, along with your ideas to it.

Extend is used for classes,here,you are extending something that already exists by adding more functionality to it.

A few more notes:

an interface can extend another interface.

And when you need to choose between implementing an interface or extending a class for a particular scenario, go for implementing an interface. Because a class can implement multiple interfaces but extend only one class.

9
votes

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}
8
votes

In the most simple terms extends is used to inherit from a class and implements is used to apply an interface in your class

extends:

public class Bicycle {
    //properties and methods
}
public class MountainBike extends Bicycle {
    //new properties and methods
}

implements:

public interface Relatable {
    //stuff you want to put
}
public class RectanglePlus implements Relatable {
    //your class code
}

if you still have confusion read this: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html

7
votes

When a subclass extends a class, it allows the subclass to inherit (reuse) and override code defined in the supertype. When a class implements an interface, it allows an object created from the class to be used in any context that expects a value of the interface.

The real catch here is that while we are implementing anything it simply means we are using those methods as it is. There is no scope for change in their values and return types.

But when we are extending anything then it becomes an extension of your class. You can change it, use it, reuse use it and it does not necessarily need to return the same values as it does in superclass.

5
votes

Classes and Interfaces are both contracts. They provide methods and properties other parts of an application relies on.

You define an interface when you are not interested in the implementation details of this contract. The only thing to care about is that the contract (the interface) exists.

In this case you leave it up to the class which implements the interface to care about the details how the contract is fulfilled. Only classes can implement interfaces.

extends is used when you would like to replace details of an existing contract. This way you replace one way to fulfill a contract with a different way. Classes can extend other classes, and interfaces can extend other interfaces.

3
votes

Extends is used when you want attributes of parent class/interface in your child class/interface and implements is used when you want attributes of an interface in your class.

Example:

  1. Extends using class

    class Parent{

    }

    class Child extends Parent{

    }

  2. Extends using interface

    interface Parent{

    }

    interface Child extends Parent{

    }

  3. Implements

interface A{

}

class B implements A{

}

Combination of extends and implements

interface A{

}

class B

{

}

class C implements A,extends B{

}
2
votes

extends

  • class extends only one class
  • interface extends one or more interfaces

implements

  • class implements one or more interfaces
  • interfaces 'can not' implements anything

abstract classes also act like class, with extends and implements

1
votes

Those two keywords are directly attached with Inheritance it is a core concept of OOP. When we inherit some class to another class we can use extends but when we are going to inherit some interfaces to our class we can't use extends we should use implements and we can use extends keyword to inherit interface from another interface.

1
votes

In Java a class(sub class) extends another class(super class) and can override the methods defined in the super class.

While implements is used when a class seeks to declare the methods defined in the Interface the said class is extending.