OOP: Abstraction

Abstraction is one of the four Object Oriented Concepts. This article briefly explains the concept and the purpose of abstraction. In object oriented programming all the problems are mapped as an interaction of objects. However, there are some real world objects which are just abstract ideas. For example take Vehicle as an object. In real world do we have an object Vehicle? Let me to briefly explain my question. If I say car, in your mind you may have an image of car. If I say motorbike, you may have a mind picture of a motorbike. If I say Vehicle, what kind of image you have in your mind? Nothing, because Vehicle is just a grouping name used in real world. Rather than saying I have a car and a motorbike, I can say I have two vehicles. That is the only purpose of having a term Vehicle.

There is something more... All of us know that if there is a vehicle, we can drive it. However, we do not know the way to drive a vehicle until we know the actual object. If it is not clear enough, try to answer these questions.
1. How to drive a car?
    Use steering wheel....
    2. How to drive a motorbike?
        Use handlebars....
      3. How to drive a vehicle?
          ???
      It shows that all the Vehicles have a behavior drive. It shows that, there are some rules or structures for the abstract entities but we cannot implement them until we know the sub type of those abstract entities. Lets implement this model in Java. Based on the requirements, a Car class can be something like this.
      public class Car {
          public void drive() {
              System.out.println("Use steering wheel");
          }
      }
      Same as the car we can define a Motorbike as shown below.
      public class Motorbike {
          public void drive() {
              System.out.println("Use handlebars");
          }
      }
      Now, how can we implement a Vehicle in Java? For vehicle, there must be a method drive but we do not know the implementation until we know the sub type. Java allows to create a method without the implementation which is defined as the abstract method.
      public abstract class Vehicle {
          /**
           * Implementation of drive method is unknown for Vehicle.
           * Notice that the method is terminated with a semicolon.
           */
          public abstract void drive();
      }
      In the above code, notice that there is a keyword abstract in the method and class declarations. In Java if a class has at least one abstract method then the class must be defined as an abstract class as shown above.

      In real world there are no actual vehicles. Then in programming world also we should not be able to create an object of Vehicle. That is true for abstract class; we cannot instantiate an abstract class. The sample code given below is an example of invalid code. If you try to compile this code you will get a compile time error.
      public class VehicleDemo {
          public static void main(String[] args) {
              Vehicle vehicle = new Vehicle();    // Compile time error
          }
      }
      Only purpose of Vehicle class is providing a grouping facility. Therefore, using this Vehicle class any sub classes can be created but the top most non-abstract sub classes in the hierarchy must provide the implementation of the abstract methods defined in the super class (The same method has to be defined in the sub classes with a body as shown here).
      public class Car extends Vehicle {
          /**
           * Car class is a non-abstract sub class of Vehicle.
           * Must override the drive method.
           */
          public void drive() {
              System.out.println("Use steering wheel");
          }
      }
      public class Motorbike extends Vehicle {
          /**
           * Motorbike class is a non-abstract sub class of Vehicle.
           * Must override the drive method.
           */
          @Override
          public void drive() {
              System.out.println("Use handlebars");
          }
      }
      public class VehicleDemo {
          public static void main(String[] args) {
              Vehicle car = new Car();
              Vehicle motorbike = new Motorbike();
              doDrive(car);   // Use steering wheel
              doDrive(motorbike); // Use handlebars
          }
      
          public static void doDrive(Vehicle vehicle) {
              vehicle.drive();
          }
      }
      Even though we cannot instantiate the abstract classes, they also have constructors. As an example look at the following Vehicle class and its sub class Car, where the constructor is used to pass the number of wheels of that vehicle.
      public abstract class Vehicle {
          private int noOfWheels;
      
          /**
           * Abstract class can have constructor.
           * @param  noOfWheels Number of wheels of this Vehicle
           */
          public Vehicle(int noOfWheels) {
              this.noOfWheels = noOfWheels;
          }
      
          /**
           * Implementation of drive method is unknown for Vehicle.
           * Notice that the method is terminated with a semicolon.
           */
          public abstract void drive();
      }

      public class Car extends Vehicle {
      
          public Car() {
              super(4);   // Call super class constructor
          }
      
          /**
           * Car class is a non-abstract sub class of Vehicle.
           * Must override the drive method.
           */
          public void drive() {
              System.out.println("Use steering wheel");
          }
      }
      For the complete project click here.

      There are some more rules related to abstract methods and classes.

      Rule #1:
      In Java an abstract-class can have zero to more abstract methods and any number of non-abstract methods, but if a class has at-least one abstract method, then the entire class must be an abstract class.

      Rule #2:
      abstract and final keywords cannot be used together.
      Final methods are not allowed to override but the important condition of abstract method is: sub classes must override the method. Therefore, final and abstract cannot be used together.
      /**
       * WARNING:
       * Compile time error due to final abstract class and final abstract method.
       */
      public final abstract class AbstractWithFinal {
          public final abstract void doStuff();
      }

      Rule #3:
      abstract and static keywords cannot be used together.
      Static methods are not permitted for inheritance, so there are no way to override static methods. On the other hand abstract methods depended on method overriding so static and abstract cannot be used together.
      /**
       * WARNING:
       * Compile time error due to static abstract method.
       */
      public abstract class AbstractWithStatic {
          public static abstract void doStuff();
      }

      Rule #4:
      Abstract method cannot be private.
      Same as static method, inheritance is not allowed for private method. So private and abstract cannot be used together.
      /**
       * WARNING:
       * Compile time error due to private abstract method.
       */
      public abstract class AbstractWithPrivate {
          private abstract void doStuff();
      }

      Rule #5:
      The direct sub abstract classes do not need to override the abstract method of their super class; suppose if they override the super class' abstract method, the upcoming non-abstract classes do not need to provide the implementation.
      /**
       * Abstract class Account with two abstract methods.
       */
      abstract class Account {
          /**
           * Abstract method.
           */
          public abstract void interest();
      
          /**
           * Abstract method.
           */
          public abstract boolean isChequeAvailable();
      
          /**
           * Non-abstract method.
           * An abstract class can have any number of non-abstract methods.
           */
          public String getName() {
              String accName = this.getClass().toString().replace("class ", "");
              return accName;
          }
      }
      
      /**
       * Abstract sub class of Account.
       * Overrides only one abstract method: isChequeAvailable.
       * Sub classes do not need to override isChequeAvailable.
       */
      abstract class SavingsAccount extends Account {
          @Override
          public boolean isChequeAvailable() {
              return false;
          }
      }
      
      /**
       * Non-abstract sub class of SavingsAccount.
       * No need to override isChequeAvailable.
       * Must override the abstract method interest.
       */
      class ChildrensSavingsAccount extends SavingsAccount {
          @Override
          public void interest() {
              System.out.println("Interest: 5.0%");
          }
      }
      For the complete project click here.

      Sample Problem
      In the last two articles we have enhanced the VeterinaryDoctor class and the modified code is provided here. This time notice that the Animal class has a method treatment but the implementation of this method is left empty because we do not know the way to treat an Animal. The implementation of this method is provided in the sub classes Dog and Cat because we can define a treatment methodology to the Cat and Dog. Apply the abstraction to Animal class, in order to prohibit object creation of Animal and to clearly define that there is no implementation for treatment method in the Animal class.

      To compare your solution click on this link.

      Find the source codes at Git Hub.

      The complete Object Oriented Programming article series are available here:
      Object Oriented Programming:
                  Encapsulation
                  Inheritance
                  Polymorphism
                  Abstraction
      Previous
      Next Post »

      Contact Form

      Name

      Email *

      Message *