Difference between Interface and Abstract Class [OOP]- Hannah Okwelum

ยท

3 min read

I will try to explain this concepts as clear as possible, don't worry if you've never used it just follow along. ๐Ÿ˜Š

All examples below are in Php programming language ๐Ÿ˜Š๐Ÿ˜Š

Interface

An Interface in OOP is a set of rules that a class must implement. In other words, if a class must use a specific interface they must implement the rules in that interface. This rules are methods without body or without actual implementation. Makes sense?

Let me go further; let's say you got a new job and if you must accept that offer, you must sign a contract. The contract in this instance is an interface. And it is a must you sign the contract if you must accept the job.

More light.

interface NewHireInterface
{
      public function signContract();
}

class NewCustomerSuccess implements NewHireInterface
{
    public function signContract(){
        return "signed";
    }
}

class NewStoreKeeper implements NewHireInterface
{
    public function signContract(){
        return "not signed";
    }
}

From the implementation above you can see that they both implemented the signContract method from the interface because it is a must as long as the classes implemented the interface.

Why is this important?

$test1 = new NewCustomerSuccess();
return $test1->signContract();
$test2 = new NewCustomerSuccess();
return $test2->signContract();

From the above code snippet, you can see I called the signContract method on both classes because they implemented the same interface and the interface has a signContract rule.

Abstract Class

An Abstract class behaves like its name, just like abstract nouns whereby you cannot see it but can feel it same with abstract class, you cannot create objects from it but you can extend it because you feel it is available after creating it. An abstract class must contain at least an abstract method. When I say abstract method, I mean a method without body just like an interface.

abstract class AbstractClass
{
// All classes that extend this must define this method
abstract protected function getGender();

//normal method
 public function logout()
  {
    //your code
   }
}

class Adam extends AbstractClass
{
    public function getGender()
    {
        return 'Male';
     }
}

An abstract class must have one abstract method and it cannot be instantiated. Like below.

$adam = new AbstractClass(); you get this: Fatal error: Uncaught Error: Cannot instantiate abstract class

It can have a constructor on like the Interface that shouldn't have a constructor. If you are going to be using an abstract class just because you want to declare an abstract method, it is best you use an Interface.

An Interface can only consist of abstract methods, the methods in an interface cannot have body but an abstract class must have at least one abstract method with a key word abstract.

cheers