PHPBuilder - OO Design: Abstract Classes Page 5



RSS Twitter
Articles Application Architecture

OO Design: Abstract Classes - Page 5

by: Jonathan Griffin
|
February 10, 2003

Example: Object Hierarchy

We want to provide an abstract class that will live at the top of our object hierarchy. This class will define core behavior that all classes in our hierarchy should implement. We will call this top-level class Object. I realize the creativity is somewhat lacking. We have identified 2 core behaviors that we would like to define in our abstract class: (1) returning a string representation of an object, and (2) comparing an instance of one object to that of another object. Here is a look at our abstract class.

<?php
class Object
{
  function 
Object()
  {
    
// Enforce abstract behavior.
    
if ( !is_subclass_of($this"Object") ) {
      
trigger_error("Object instantiation from non subclass."E_USER_ERROR);
      return 
NULL;
    }
  }
  
  function 
toString() {}
  
  function 
equals($object)
  {
    return (
$this === $object);
  }
}
?>
Here we have defined an abstract class Object on which we can build our object hierarchy. Let's take a look at this example in action. Imagine we are designing a human resources application. One obvious class in our model would be an Employee class. For the OO purists, you could model a Person and let each person wear an Employee hat through composition, but we'll save that for another discussion. Let's take a look at our Employee class.

<?php
class Employee extends Object
{
  
// Member variables.
  
var $_id;
  var 
$_ssn;
  var 
$_firstName;
  var 
$_lastName;
  
  function 
Employee($id$ssn$firstName$lastName)
  {
    
// Assign member variables.
    
$this->_id        $id;
    
$this->_ssn       $ssn;
    
$this->_firstName $firstName;
    
$this->_lastName  $lastName;
  }
  
  function 
toString()
  {
    
$info "ID: ".$this->_id."\n";
    
$info .= "SSN: ".$this->_ssn."\n";
    
$info .= "FirstName: ".$this->_firstName."\n";
    
$info .= "LastName: ".$this->_lastName."\n";
    return 
$info;
  }
}
?>
Notice our Employee class has provided implementation for the toString() method. No implementation for the equals() method was provided, since the Object class provides a sufficient one. However, if the implementation did not suffice, we could have provided our own version of equality checking. As we further design our object hierarchy based on Object, we know that all our classes will have 2 common behaviors: equals() and toString().

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Jonathan Griffin

Comment:



Comment:

(Maximum characters: 1200). You have characters left.