Sobes.tech
Junior

What is an abstract class?

sobes.tech AI

Answer from AI

An abstract class is a class that cannot be instantiated directly, meaning you cannot create an object of it using new. It is intended to be used as a base class for other classes (derived classes).

Main characteristics of an abstract class:

  • Declared with the keyword abstract.
  • Can contain both abstract and regular (concrete) methods.
  • Abstract methods are declared with the keyword abstract and have no body (implementation). They must be implemented in non-abstract derived classes.
  • Can contain constant values and properties.
<?php

abstract class AbstractClass
{
    // Abstract method - must be implemented in the derived class
    abstract protected function abstractMethod();

    // Regular method
    public function concreteMethod()
    {
        echo "This is a concrete method\n";
    }
}

class ConcreteClass extends AbstractClass
{
    // Implementation of the abstract method
    protected function abstractMethod()
    {
        echo "This is the implementation of the abstract method\n";
    }
}

// Cannot instantiate an abstract class
// $obj = new AbstractClass(); // Error

// Can instantiate a concrete class
$obj = new ConcreteClass();
$obj->abstractMethod();
$obj->concreteMethod();

Abstract classes are used to define a common interface and functionality for a group of related classes, leaving implementation details to specific derived classes. From the consumer's side, you can work with objects of derived classes using the type of the base abstract class, which ensures polymorphism.

What is an abstract class? — PHP - sobes.tech