Home Tutorials Abstract classes

Abstract classes

  previous next
March 08, 2009 by Victor    

Obviously the concept of the interface did not cover all possible holes thus, abstract classes were created. An abstract class is one that cannot be instantiated. Elementary my dear Watson, classes that cannot be instantiated, what for? Well, it does have an analogy to real things I would say, not everything can be instantiated in our material world. It is the same idea as with interfaces, abstract classes define generic attributes of objects. You first define generic properties and then you provide the functionality it is required in child classes.

Let’s say for now that our users are divided into three main categories, registered users, administrators and guests. Since each user type requires different properties and methods, we have three classes inheriting the User class. Now, we don’t actually like having the User class be instantiated, all users should fall into one of these three categories. Thus, the User class should better be declared as abstract. Reasonably enough, all users do have some common properties and methods, say all have an IP address therefore we may declare all common properties and methods in the User class.

The second purpose of abstract classes is to enforce the implementation of certain functionality. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class. So, the use of an abstract class just ensures that all child classes will provide the required functionality.

See the example, may clear the fog a bit.

<?
abstract class User
{
    protected $ip;
 
    # This method is not abstract
    protected function printip ()
    {
        print $this->ip;
    }
 
    # This method is abstract 
    # Each child class should provide an implementation for it
    abstract protected function printUser();
}
 
class Registered extends User
{
    var $name;
    var $username;
    var $email;
    var $id;
 
    function __construct($newname,$lastid) 
    {
       $this->name = $newname;
       $this->id = ++$lastid;
    }
 
    public function printUser()
    {
       print "\n $this->name [$this->username]";
    }
} 
 
class Admin extends User
{
    var $mobile;
    var $extension;
 
    function __construct($newmobile,$newextension)
    {
       $this->mobile = $newmobile;
       $this->extension = $newextension;
    }
 
    public function printUser()
    {
       print "\n mob. $this->mobile - ext. $this->extension";
    }
}
 
class Guest extends User
{
    var $sessionid;
 
    function __construct($newsessionid)
    {
       $this->sessionid = $newsessionid;
    }
 
    public function printUser()
    {
       print "\n session id $this->sessionid";
    }
}
 
### create a new user
$harris = new Admin("9600888888","4444");
$harris->printUser();
$guestA = new Guest("123141");
$guestA->printUser();
?>

Add comment


Security code
Refresh