Curs 03
Curs 03
class Pacient {
public void is_treated_by (Doctor d) {
...
}
}
AGREGARE
gruparea a mai multe modele intr-o structura
comuna
has-a (Team T has Player P)
durata de viata separata, pot fi recombinate
class Player {
...
}
}
INHERITANCE BREAKS ENCAPSULATION
But class inheritance has some disadvantages, too. First, you can't change the implementations inherited from
parent classes at run-time, because inheritance is defined at compile-time. Second, and generally worse,
parent classes often define at least part of their subclasses' physical representation. Because inheritance
exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks
encapsulation"
Object composition is defined dynamically at run-time through objects acquiring references to other objects.
Composition requires objects to respect each others' interfaces, which in turn requires carefully designed
interfaces that don't stop you from using one object with many others. But there is a payoff. Because objects
are accessed solely through their interfaces, we don't break encapsulation. Any object can be replaced at
runtime by another as long as it has the same type. Moreover, because an object's implementation will be
written in terms of object interfaces, there are substantially fewer implementation dependencies.
That leads us to our second principle of object-oriented design:
Favor object composition over class inheritance