Object Oriented Programming » History » Version 7
Amber Herold, 08/02/2011 12:50 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 | 7 | Amber Herold | * collection of _attributes_ and _behaviors_ |
7 | * defined as a _class_ |
||
8 | |||
9 | h2. Encapsulation |
||
10 | |||
11 | |||
12 | h2. Inheritance |
||
13 | |||
14 | * reuse code by basing an object on another object |
||
15 | * terminology |
||
16 | ** Superclass, base class, parent class |
||
17 | ** Subclass, derived class, child class |
||
18 | * examples |
||
19 | ** parent: Animal, children: Person, Cat, Fish |
||
20 | ** parent: MotorVehicle, children: Car, Truck, Bus, Tractor |
||
21 | ** parent: Shape, children: Ellipse, Rectangle, Triangle, Cone |
||
22 | * _Child classes_ inherit attributes and behaviors from _parent classes_ |
||
23 | 3 | Amber Herold | |
24 | 1 | Amber Herold | |
25 | h2. Polymorhism |
||
26 | |||
27 | h3. PHP example |
||
28 | |||
29 | <pre> |
||
30 | interface IAnimal { |
||
31 | function getName(); |
||
32 | function talk(); |
||
33 | } |
||
34 | |||
35 | abstract class AnimalBase implements IAnimal { |
||
36 | protected $name; |
||
37 | |||
38 | public function __construct($name) { |
||
39 | $this->name = $name; |
||
40 | } |
||
41 | |||
42 | public function getName() { |
||
43 | return $this->name; |
||
44 | } |
||
45 | } |
||
46 | |||
47 | class Cat extends AnimalBase { |
||
48 | public function talk() { |
||
49 | return 'Meowww!'; |
||
50 | } |
||
51 | } |
||
52 | |||
53 | class Dog extends AnimalBase { |
||
54 | public function talk() { |
||
55 | return 'Woof! Woof!'; |
||
56 | } |
||
57 | } |
||
58 | |||
59 | $animals = array( |
||
60 | new Cat('Missy'), |
||
61 | new Cat('Mr. Mistoffelees'), |
||
62 | new Dog('Lassie') |
||
63 | ); |
||
64 | |||
65 | foreach ($animals as $animal) { |
||
66 | echo $animal->getName() . ': ' . $animal->talk(); |
||
67 | } |
||
68 | </pre> |
||
69 | 2 | Amber Herold | |
70 | h3. Python Example |
||
71 | |||
72 | <pre> |
||
73 | class Animal: |
||
74 | def __init__(self, name): # Constructor of the class |
||
75 | self.name = name |
||
76 | def talk(self): # Abstract method, defined by convention only |
||
77 | raise NotImplementedError("Subclass must implement abstract method") |
||
78 | |||
79 | class Cat(Animal): |
||
80 | def talk(self): |
||
81 | return 'Meow!' |
||
82 | |||
83 | class Dog(Animal): |
||
84 | def talk(self): |
||
85 | return 'Woof! Woof!' |
||
86 | |||
87 | animals = [Cat('Missy'), |
||
88 | Cat('Mr. Mistoffelees'), |
||
89 | Dog('Lassie')] |
||
90 | |||
91 | for animal in animals: |
||
92 | print animal.name + ': ' + animal.talk() |
||
93 | |||
94 | # prints the following: |
||
95 | # |
||
96 | # Missy: Meow! |
||
97 | # Mr. Mistoffelees: Meow! |
||
98 | # Lassie: Woof! Woof! |
||
99 | </pre> |