01 November 2013

abstract class in OOPS explained

Abstract classes plays an important role in OOPS class design. In this post let's discuss below:

  1. What is abstract class?
  2. How to define a abstract class?
  3. When to use a abstract class?
  4. Abstract classes in .NET framework
  5. How to representing Abstract class in UML?
  6. Abstract classes in Design Patterns

Let's discuss each of these in detail to understand about abstract class better.

What is abstract class?

An Abstract class cannot be instantiated and it is meant to be inherited by other classes. An abstract class usually have both concrete and abstract methods.

  • Methods in an abstract class with the implementation are called concrete methods. Concrete methods are also called as non abstract methods.
  • Methods in the abstract class with just declaration are called abstract methods.
  • An abstract class can have zero or more number of abstract methods. But a class containing an abstract method should be marked as abstract. Otherwise there will be compile time error:

    method is abstract but it is contained in non-abstract.

How to define a abstract class?

public abstract class Car
   public abstract void Drive();
  • "abstract" keyword is used to define an abstract class.
  • Methods can be made abstract by declaring them with "abstract".
  • Trying to instantiate an abstract class will give a compile time error.

    ???Abstract class cannot be instantiated.??

When to use a abstract class?

When we are designing a base class, we should ask a question to our-self, can this be a abstract class? Answer depends!!!. If a class in question doesn't have real life usage or no one uses the class as it is, then mark it has abstract class and put common logic which is applicable to all the derived classes in a non abstract methods.

For example, when you are designing a Doctor class, make it concrete class not a abstract class. Just an MBBS doctor can treat patients without any specialization (e.g, Surgeon); so he/she has real life usage on just being a Doctor. So making the doctor class abstract doesn't make sense.

Where as consider an example of vehicle. Vehicle will have a chassis, wheels, engine, etc. But so one buys a vehicle with just these basics parts. People buy specialized forms of Vehicle i.e, Car, Bus, Truck, etc. So designing Vehicle as abstract class doesn't make sense. And the specialized classes designers, like Car, will derive from the base Vehicle class and adds features to make it a Car. Here Car is concrete class and Vehicle is abstract class.

Abstract classes in .NET framework

How to representing Abstract class in UML?

Abstract classes in Design Patterns