Author

Abstract Classes and Interfaces

Image

by Samarth Sinha on 2017-10-12 19:15:44

Abstract Classes

An abstract class is a class that is declared abstract—it may or may not include abstract methods.
You cannot create an object of an abstract class. They can only be inherited and by another class. An abstract method is a method that is declared but not defined, like this:
abstract function xyz();

If you want to create an abstract function you have to declare that class abstract. When an abstract class is subclassed, it should contain implementations for all of the abstract methods in its parent class, if not, then the subclass must also be declared abstract.

Interfaces

An interface is a blueprint of a class, it can only contain static constants and abstract methods. All functions in interfaces are by default abstract, you need not put the abstract keyword before the function declaration the will automatically be abstract.
Example:

Interface I1 {
    function name();
}


Which should you use, abstract classes or interfaces?

  • Use of abstract class:
  1. ​Share code among several closely related classes.
  2. The classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  3. Declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  • Use of Interface:
  1. You expect that unrelated classes would implement your interface.
  2. To specify the behavior of a particular data type, but not concerned about who implements its behavior.

 


About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.