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

2021-6-3 anglehua

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

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

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


Powered by emlog 京ICP备15036472号-3 sitemap