Tuesday, April 5, 2016

Java OOP - Abstraction


Here we go, Abstraction in Java. Probably the hardest concept to understand when you start with OOP. I have to admit it took me a while to really figure out how this concept works and how useful can be.

Abstraction is the process of hiding the implementation details and showing only functionality to the user. In Abstraction we deal with ideas rather than events. Still confused? I know your pain =)

Abstraction in Java is achieved by using interface and abstract classes in Java. In this case, interface or abstract class is "something" that is not complete, something not concrete. So if we want to use interface or abstract class, we are going to need to extend and implement an abstract method with concrete behavior. Got it? not yet? for real? ...no problem, I'll keep explaining..

Imagine you have to define a class "table" but, you still don't know what kind of table it would be. It can be a night table, dinner table, 6 legged table, round table, etc... So, what do you do?, you define an abstract class table, why? because you still don't know what you are going to need later; you have the idea but nothing concrete yet. Just define something abstract.

Another example can be declaring an abstract class Vehicle (which is an abstract idea), then we can have "car", "truck" or "boat" class which can extend Vehicle...

Here is an example of the code:

abstract class Vehicle
{
   public abstract void engine();  
}
public class Car extends Vehicle {
    
    public void engine()
    {
        System.out.println("Car engine");
        //car engine implementation
    }
    
    public static void main(String[] args)
    {
        Vehicle v = new Car();
        v.engine();
        
    }
}


Output
Car engine


Things to remember about abstract class:

  • Can not be instantiated, that's why can not be used directly
  • Abstract classes may or may not contain abstract methods
  • But if a class have at least one abstract method, then the class must be declared abstract
  • If any class contains abstract methods then it must implement all the abstract method of the abstract class







No comments:

Post a Comment