What is the difference between implementations and Extends and when are they used respectively?

Asked 2 years ago, Updated 2 years ago, 72 views

What is the difference between implementations and Extends and when are they used respectively? It's a basic question, but I don't know the difference between these two. Please explain it so that it's easy to understand.

java design extends implements

2022-09-22 22:28

1 Answers

extends is an extension of the class, and implementations is an interface implementation of the interface.

The difference between an interface and a normal class is that the interface does not have to implement the methods you define. You can implement the methods defined on the interface in the class that inherits the interface.

C++ allows multiple inheritance, but Java does not support multiple inheritance. So it provides an interface as an alternative.

public interface ExampleInterface{
    public void do();
    public String doThis(int number);
 }
 public class sub implements ExampleInterface{
     public void do(){
       //specify what must happen
     }
     public String doThis(int number){
       //specfiy what must happen
     }
 }

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


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

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

I recommend you to look for data on dynamic binding and polymorphism once

.


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.