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