Implements vs Extends: When To Use In Java?

Here we are going to differentiate between Implements and Extends, and When To Use In Java? Implements are used for interface inheritance and extended if used for class inheritance.

Implements vs Extends

 What Are Implements?

It is a keyword used for inheriting the properties or member functions along with variables in an interface from another interface and that other interface is called as parent interface and where they are inherited is called the child interface.

Use Of Implements

We use the interface to get the class purely or 100% abstract, Where all the member functions along with all the variables become abstract whereas the interface is nothing but just a blueprint of the class which is abstract.

It helps in getting multiple inheritance and multiple inheritances are not supported in classes due to ambiguity errors so we can achieve that user interface.

to use the interface follow the example given below

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

Here we can see how ExampleInterface implements sub.

What is Extends

Extends is a keyword used for inheriting the properties of the parent class into the child class where it is used to access the member functions of parents and child in both classes.

Use Of Extends

Extends are used for for inheriting the parent class. It is just a keyword just like implements to establish a link between parent and child class.

Let us understand in better ways with an example.

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

We can clearly see how a parent class SuperClass is being inherited into child class SunClass using the keyword extends.

 

Learn More about Implements vs Extends: When To Use In Java? at Extends and Implements

Also, visit at JAVA TUTORIAL for Class for more information about java and solve your problems.

Leave a Comment

%d bloggers like this: