Project

General

Profile

Object Oriented Programming » History » Revision 6

Revision 5 (Amber Herold, 08/02/2011 12:29 PM) → Revision 6/21 (Amber Herold, 08/02/2011 12:37 PM)

h1. Object Oriented Programming 

 h2. Objects 

 * often models a real-world thing - person, animal, shape, car  
 * collection of *attributes* and *behaviors* 
 * defined as by a class 


 h2. Polymorhism 

 h3. PHP example 

 <pre> 
 interface IAnimal { 
     function getName(); 
     function talk(); 
 } 
 
 abstract class AnimalBase implements IAnimal { 
     protected $name; 
 
     public function __construct($name) { 
         $this->name = $name; 
     } 
 
     public function getName() { 
         return $this->name; 
     } 
 } 
 
 class Cat extends AnimalBase { 
     public function talk() { 
         return 'Meowww!'; 
     } 
 } 
 
 class Dog extends AnimalBase { 
     public function talk() { 
         return 'Woof! Woof!'; 
     } 
 } 
 
 $animals = array( 
     new Cat('Missy'), 
     new Cat('Mr. Mistoffelees'), 
     new Dog('Lassie') 
 ); 
 
 foreach ($animals as $animal) { 
     echo $animal->getName() . ': ' . $animal->talk(); 
 } 
 </pre> 

 h3. Python Example 

 <pre> 
 class Animal: 
     def __init__(self, name):      # Constructor of the class 
         self.name = name 
     def talk(self):                # Abstract method, defined by convention only 
         raise NotImplementedError("Subclass must implement abstract method") 
 
 class Cat(Animal): 
     def talk(self): 
         return 'Meow!' 
 
 class Dog(Animal): 
     def talk(self): 
         return 'Woof! Woof!' 
 
 animals = [Cat('Missy'), 
            Cat('Mr. Mistoffelees'), 
            Dog('Lassie')] 
 
 for animal in animals: 
     print animal.name + ': ' + animal.talk() 
 
 # prints the following: 
 # 
 # Missy: Meow! 
 # Mr. Mistoffelees: Meow! 
 # Lassie: Woof! Woof! 
 </pre>