Project

General

Profile

Object Oriented Programming » History » Version 2

Amber Herold, 08/02/2011 12:15 PM

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