Saturday, December 13, 2014

Get the Difference Between Abstract class vs Interfaces in PHP

Abstract class vs interfaces is the most favorite question of all interviewers. They generally want to know what is abstract class and interfaces. Let discuss both of then one by one as well as differences.
Interfaces
An interface is an agreement. When class A implement interface B then it means it contains same public methods with interface B has.

Example of Interface :-

interface cacheInterface {

       public function get($key);

       pubic function set($key,$value);

}

class Memcache implements cacheInterface {

     public function get($key){

         // Define this method

      }

     public function set($key,$value){

       // Define this method

     }

In above example, I have created one cache Interface which has two public method get and set. Now Memcache class, which implements cache Interface define the get and set method.

Abstract Class :-

It is used to define a basic skeleton or blueprint. A class which extends abstract class must define some or all of it’s abstract methods.

abstract class car{

   abstract public function modelType();

   public function wheelCount() {

      echo "I have four wheels";
    }

}

class HondaCity extends car{

    public function modelType(){

        echo "HondaCity";
    }
}

$data = new HondaCity;

$data->modelType();

$data->wheelCount();

Abstract class Vs Interfaces :-

1. An abstract class is used to define the blueprint for child classes. It may contain one or more abstract methods.

On another hand, An interface is a contract. All the method defined as an interface is fully abstract. The child class which implements the interface needs to define all of its method.

2. A class can extend only one abstract class whereas a class can implement multiple interfaces.

3. You can define variables and concrete method in abstract class. On another side, In interface all the methods are abstract. You cannot define variables. You can define constants in interface.

4. If you need common base class and add methods in the future, then an abstract class is a very good. You cannot apply this thing in interfaces, otherwise all the classes that interface will have to modify to implement the new methods.

0 comments:

Post a Comment