Actions
Object Oriented Programming » History » Revision 12
« Previous |
Revision 12/21
(diff)
| Next »
Amber Herold, 08/02/2011 01:08 PM
Object Oriented Programming¶
Objects¶
- An object often models a real-world thing - person, animal, shape, car
- Collection of attributes and behaviors
- Defined as a class with member variables and methods
- An instance of a class
Encapsulation¶
Inheritance¶
- Reuse code by basing an object on another object
- Terminology
- Superclass, base class, parent class
- Subclass, derived class, child class
- Examples
- parent: Animal, children: Person, Cat, Fish
- parent: MotorVehicle, children: Car, Truck, Bus, Tractor
- parent: Shape, children: Ellipse, Rectangle, Triangle, Cone
- Child classes inherit attributes and behaviors from parent classes
- Child classes may override behaviors inherited from parent classes by providing it's own implementation of a method.
- An abstract method in a parent class does not have an implementation. Child classes MUST provide an implementation to be instantiated.
- An abstract class has at least one abstract method and cannot be instantiated.
- A virtual method in a parent class provides a default implementation that MAY be overriden by the child classes.
Polymorhism¶
PHP example¶
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();
}
Python Example¶
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!
Updated by Amber Herold about 14 years ago · 21 revisions