Tuesday, February 11, 2014

What is Abstraction?

I understand when you are studying basic oop concepts; bigger and complex looking words like Abstraction or Encapsulation can blow up your mind. When already Abstract Classes are messing with your coding knowledge, this encapsulation thing gives headache. Well, here I am to explain you in simple word what is encapsulation in OOP.

What is Abstraction?

Almost everyone of you have driven a car once in a while. Have you really thought when I put a break on what happens inside a car that makes it reduce the speed and stop suddenly? Have you thought how that machinery inside the car works? No! Because you have just cared about putting break on and reduce the speed. This is abstraction!



Abstraction is hiding irrelevant details from viewer's perspective. In case of example of car, you are a user and automobile engineer have taken enough efforts to hide details inside the car and just give you one part to hit on when you need to reduce the speed. 

Now how to achieve abstraction in object oriented languages? Abstract methods are the methods which have only declaration but no definition. In other words, abstract methods are needed to be overridden by child class in order to use them. A class having such methods is called as Abstract Class. You may refer my previous post to understand when to use an abstract class

To understand what is abstraction you need to understand real life examples about it and do some coding in your favorite object oriented language. And if you still don't get it, feel free to comment below and I will help you out!

Sunday, February 9, 2014

When to Use Abstract Class?

To understand when to use an Abstract Class first let us understand what is abstract class. 

Abstract Class

Abstract Class is a class that cannot be instantiated. In other words, you cannot create an object of abstract class. 

public abstract class Shape{

//some methods and variables

}

Public main class
Shape S1 =  new Shape(); //This entry is invalid as you cannot create object of abstract class.

Abstract class can contain abstract method as well as non abstract methods. Now, these abstract methods can only have declarations.

When a child class inherits abstract class, it must inherit abstract methods in the class.  Parent class has methods with declaration only which are abstract as well as methods with definition also which guarantees that they are being used as it is and cannot be changed. While, methods which are only declared offer flexibility to be used as per requirements of child class. 

When to use an abstract class?

An abstract class must be used when different related components are intended to use set of methods that are functionally same and at the same time offer flexibility to be modified as per needs. You can check examples of abstract class implementation in C# and Java to understand this concept clearly.