Object-Oriented Programming:  Abstraction

Object-Oriented Programming: Abstraction

Abstraction is hiding complex code implementation and only exposing the functionality. A real-life example of abstraction is the sending of an email. As a sender, we do not care about the internal mechanism of sending an email. All we care about is when we provide the correct email address, email content, and press send, the email is sent to the intended recipient. We only know how the sending of email works and not how it sends the email. Read more on all four concepts of Object-Oriented Programming.

Let us look at how to implement abstraction. We can achieve abstraction either by an interface or abstract class. Below I demonstrate an example of abstraction in Java using an interface.

Scenario: We want to check the availability of a Course and a Car.

Step 1: Create an interface

public interface Available {

    void checkAvailability(String name);
}

Step 2: Implement the Interface

class Course implements Available {

    public void checkAvailability(String name) {

        if (CourseType.JAVA.name().equalsIgnoreCase(name))
            System.out.println("Java courses available");
        else if (CourseType.PYTHON.name().equalsIgnoreCase(name))
            System.out.println("Python courses available");
        else
            System.out.println(name + " courses not available");
    }
}
public class Car implements Available {

    public void checkAvailability(String name) {

        if (CarName.MASERATI.name().equalsIgnoreCase(name))
            System.out.println("Maserati is available");
        else if (CarName.PORSCHE.name().equalsIgnoreCase(name))
            System.out.println("Porsche is available");
        else
            System.out.println(name + " is not available");
    }
}

Below is a demonstration of how to use abstraction in the AbstrationDemo class.

public class AbstractionDemo {

    public static void main(String[] args) {
        Available course = new Course();

        System.out.println("Checking course availability\n");
        course.checkAvailability("Java");
        course.checkAvailability("Python");
        course.checkAvailability("JavaScript");

        System.out.println("\nChecking car availability\n");
        Available car = new Car();
        car.checkAvailability("Maserati");
        car.checkAvailability("BMW");
        car.checkAvailability("Porsche");
    }
}

Results

abstract_results.PNG

When a class implements an interface it enters into a contract with the interface, so the class is obligated to perform all the functionality in the interface. In the above example, the Course and Car class implement the checkAvailability() method declared in the Available interface. This way, the checkAvailability() method implementation is hidden in the Course and Car class.

Thank you for reading, code examples can be found in github.