Tuesday, 1 January 2013

Abstraction, Encapsulation and Polymorphism


  1. Encapsulation - puts related data and functionality in one place. We can get this through classes
  2. Polymorphism - Allows values of different data types to be handled using a uniform interface.
Polymorphism can be achieved by inheriting base classes (with virtual functions) and/or by implementing interfaces.
These techniques (and others) give us abstraction, which really applies to any of the processes we use to break a problem up into smaller components.
Eg:
A highly contrived example:
public class Person {
  private int age;

  public boolean canBuyBeer() {
    return age >= 21;
  }

}
you might later change this to:
public class Person {
  private int age;
  private boolean isInUSA


  public boolean canBuyBeer() {
    if( isInUSA )
        return age >= 21;
    else
         return age >= 18;
  }

}
Encapsulation:- The rules regarding age and origin can change but the caller doesn't need to know.
Interfaces can be used to abstract out different types. Consider this:
public interface Beverage {
  public boolean containsAlchohol;
}

public class Soda implements Beverage {
  public boolean containsAlchohol {  
      return false;
  }
}
public class Beer implements Beverage {
  public boolean containsAlchohol {
       return true;
  }
}
You might update Person like:
public class Person {
  private int age;
  private boolean isInUSA


  public boolean canBuyBeverage(Beverage b) {
    if( b.containsAlchohol() ) {
       if( isInUSA )
           return age >= 21;
       else
           return age >= 18;
    }
    else {
        return true;
    }
  }

}
Now we are implementing the Polumorphism in case of Beverages.
or 
public void doSomething( List list )  
{     System.out.println( list.size() );
     list.add("Hello"); 
 } 
You might call doSomething with an ArrayList or a LinkedList. By ignoring the detail of the exact type I can focus on the big picture of what I want to do with the list.
So, by implementing these two concepts, we can achieve Abstraction.
Regards
Rajan Bansal