Sunday, September 29, 2013

Java - implements vs. extends

extends is for extending a class.

implements is for implementing an interface

Example:

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

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

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

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

Reference: http://stackoverflow.com/questions/10839131/implement-vs-extends-when-to-use-whats-the-difference

No comments:

Post a Comment