Home » Code » What are Abstract classes?

What are Abstract classes?

Posted by on March 26th, 2014

What are Abstract classes
Abstract classes are a common feature of Object Oriented Programming languages such as PHP, Java or C#. I tend to think of Abstract Classes as a way to ensure a certain level of code quality because they enforce certain standards and can reduce the amount of duplicate code that you have to write.

If you are new to programming or you aren’t familiar with many of the features of Object Oriented Programming languages, Abstract Classes can seem daunting at first. However once you are able to recognise them and you understand what their role is in the system, you soon start to realise how valuable they are.

In this post I’m going to walk you through exactly what an Abstract Class is, how to create them and when you should use them throughout your code.

As usual, all code examples will be in PHP, however these principles are actually very common in many different programming languages.

What is an Abstract Class?

An Abstract Class is basically a blueprint that should only ever be extended by child classes and not used directly. By extending the blueprint, the developer can ensure that the basic functionality is present in the child class in order for it to be functional.

Abstract Classes can not be directly instantiated as they rely on child classes to fully implement the functionality. By using an Abstract Class, a developer can ensure that any child classes that inherit from the Abstract Class will follow the same design.

How to create an Abstract Class

For example, continuing on from last week’s example of social sharing sites, imagine we have the following abstract social class blueprint:

abstract class AbstractSocialShare {

  /**
   * Authentication token
   */
  protected $token;
	
  /**
   * Get token
   * @return string
   */
  public function getToken()
  {
  return $this->token;
  }
	
	/**
   * Share
   * @return bool
   */
  abstract public function share();

}

In order so that we can switch out different social sharing sites at runtime, it’s important that all the individual social sharing classes follow the same blueprint.

As you can see in the example above, the getToken method is defined in the abstract class because this method will always be the same in each child class. This enables us to abstract this code away from the child classes so we don’t have to repeat ourselves.

The share class will be different depending on which social sharing site we are using. In this instance we must declare it as an abstract method that will be defined on the child class. By declaring it as an abstract method, we are ensuring that any other developer who wants to implement this blueprint is forced to also implement the share method.

Now we might have the following two child classes for Twitter and Facebook:

class Twitter extends AbstractSocialShare {

  public function __construct($token)
  {
    $this->token = $token;
  }

  public function share()
  {
    return $this->tweet;
  }

}

$twitter = new Twitter('twitter_token');
$twitter->share();
class Facebook extends AbstractSocialShare {

  public function __construct($token)
  {
    $this->token = $token;
  }

  public function share()
  {
    return $this->post;
  }

}

$facebook = new Facebook('facebook_token');
$facebook->share();

So as you can see both the Twitter and Facebook child classes extend the AbstractSocialShare class. This means all child classes will inherit the properties and methods of the Abstract class.

Within each child class we can implement the share method depending on how the specific child class works. This means that no matter what child class is chosen, the system will know that the class will have the share method available, the system does not need to know how the actual share method will be implemented.

When should you use Abstract Classes?

When learning programming concepts like the use of Abstract Classes, it is important to understand when to use them, not just how they work.

An Abstract Class should be used whenever you have multiple implementations of a certain bit of functionality. By using an Abstract Class, you can reduce duplication and ensure that each child class is interchangeable with one another by always having a consistent public API.

A common way to think about the use of Abstract Classes is to think about them as interchangeable types of the same thing. For example an Audi, a BMW or a Land Rover are all different types of cars and so inheriting from a AbstractCar class would make a lot of sense. If you can say to yourself, “an Audi is a type of Car, it usually make sense to structure your code around the use of an Abstract class.

Conclusion

Using Abstract classes is an important component of writing high quality maintainable code. Abstract classes act as a blueprint that can define how certain implementations should work. This simple structure goes a long way to ensuring that you write interchangeable code that can withstand the future changing requirements of a system.

Understanding how Abstract classes work and why they are used is important when you start to read through other people’s code and Open Source projects. Often when reading through a class you will need to find the source for a particular method. By understanding the common structures of classes within applications you can make your research and understanding of a new system much quicker.

Philip Brown

Hey, I'm Philip Brown, a designer and developer from Durham, England. I create websites and web based applications from the ground up. In 2011 I founded a company called Yellow Flag. If you want to find out more about me, you can follow me on Twitter or Google Plus.

  • Eduardo WB

    Great article, explained it very well, as always! Now let´s see another one explaining interfaces and other explaining when to use one instead of other. Thank you!

    • That’s exactly what next week’s post is all about :p

      • Eduardo WB

        Looking forward to next week then!
        Now, off-topic, check your G+, Philip. I sent an article suggestion. I didn´t know where to send it, but as you are there, I sent there.

        • Hmm, I didn’t see that. Could you email me at phil at ipbrown dot com?

          Thank you :)

          • Eduardo WB

            I sent you the email :)

          • Thanks Eduardo :)

  • adsas

    Can you explain the difference between abstract classes and interfaces?

  • Parsec

    Very nice explained. Looking forward to read your next article^^

  • Adrian

    Verry nice explained… A single thing I would do different is define post and tweet so some people can understand where are they comming from…

    • Thanks Adrian, yeah it’s hard to judge where to draw the line with example code. Glad it helped you :)

  • vince

    Heah Philip – you have a natural skill for education. Breaking things down and presenting them in an understandable manner. Dayle Rees is the same. Other Laravel sources rattle off code at 100 miles and hour and you are always thinking to yourself, “WTF, what was that he just said !”

    The only thing I struggle with is navigating around the site. Knowing, retrospectively, what the progressive steps are in a series. Also tracking down stuff related to the current topic. For example, 7th paragraph down you state: “continuing on from last week’s example of social sharing sites”. Well, finding last weeks stuff on social sharing is not that easy. Using your search and looking at the url for the date gave me the piece on the Factory design pattern. You used to order stuff in a list.

    Any I really appreciate what you are doing here – it is outstanding, and your teaching is so much easier to follow than so many resource.

    Many thanks !

    • Thanks Vince :)

      Yeah I agree, this current layout leaves a lot to be desired. It’s more suited to a traditional blog, rather than a learning resource website.

      The next version will be moving away from the blog format to something more centred around “courses” and series of posts. Hopefully that will make it easier to navigate around and know what has come previous and what is still to come.

      Thank you for your kind words Vince :)

  • Marcelo

    Awesome article! Well done.