the difference between interface and extend
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.
What is interface?
We can use an interface to define what an object do, but leave it up to the specific types of instances to implement how particular behavior is done.
Why is interface?
1. An interface give you the ability to specify a set of behaviors that all classes that implement the interface will share in common. Consequently, we can define variables and collections that don't have to know in advance what kind of specific object they will hold, only that they'll hold objects that implement the interface.
2. Interface is a statically typed language. This character help the compiler verify that a contract which your relies on is actually met.
3. Java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.
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
}
}
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