Object Oriented Programming » History » Version 6
Amber Herold, 08/02/2011 12:37 PM
1 | 1 | Amber Herold | h1. Object Oriented Programming |
---|---|---|---|
2 | |||
3 | 3 | Amber Herold | h2. Objects |
4 | |||
5 | 5 | Amber Herold | * often models a real-world thing - person, animal, shape, car |
6 | 4 | Amber Herold | * collection of *attributes* and *behaviors* |
7 | 6 | Amber Herold | * defined as a class |
8 | 3 | Amber Herold | |
9 | 1 | Amber Herold | |
10 | h2. Polymorhism |
||
11 | |||
12 | h3. PHP example |
||
13 | |||
14 | <pre> |
||
15 | interface IAnimal { |
||
16 | function getName(); |
||
17 | function talk(); |
||
18 | } |
||
19 | |||
20 | abstract class AnimalBase implements IAnimal { |
||
21 | protected $name; |
||
22 | |||
23 | public function __construct($name) { |
||
24 | $this->name = $name; |
||
25 | } |
||
26 | |||
27 | public function getName() { |
||
28 | return $this->name; |
||
29 | } |
||
30 | } |
||
31 | |||
32 | class Cat extends AnimalBase { |
||
33 | public function talk() { |
||
34 | return 'Meowww!'; |
||
35 | } |
||
36 | } |
||
37 | |||
38 | class Dog extends AnimalBase { |
||
39 | public function talk() { |
||
40 | return 'Woof! Woof!'; |
||
41 | } |
||
42 | } |
||
43 | |||
44 | $animals = array( |
||
45 | new Cat('Missy'), |
||
46 | new Cat('Mr. Mistoffelees'), |
||
47 | new Dog('Lassie') |
||
48 | ); |
||
49 | |||
50 | foreach ($animals as $animal) { |
||
51 | echo $animal->getName() . ': ' . $animal->talk(); |
||
52 | } |
||
53 | </pre> |
||
54 | 2 | Amber Herold | |
55 | h3. Python Example |
||
56 | |||
57 | <pre> |
||
58 | class Animal: |
||
59 | def __init__(self, name): # Constructor of the class |
||
60 | self.name = name |
||
61 | def talk(self): # Abstract method, defined by convention only |
||
62 | raise NotImplementedError("Subclass must implement abstract method") |
||
63 | |||
64 | class Cat(Animal): |
||
65 | def talk(self): |
||
66 | return 'Meow!' |
||
67 | |||
68 | class Dog(Animal): |
||
69 | def talk(self): |
||
70 | return 'Woof! Woof!' |
||
71 | |||
72 | animals = [Cat('Missy'), |
||
73 | Cat('Mr. Mistoffelees'), |
||
74 | Dog('Lassie')] |
||
75 | |||
76 | for animal in animals: |
||
77 | print animal.name + ': ' + animal.talk() |
||
78 | |||
79 | # prints the following: |
||
80 | # |
||
81 | # Missy: Meow! |
||
82 | # Mr. Mistoffelees: Meow! |
||
83 | # Lassie: Woof! Woof! |
||
84 | </pre> |