Class Invariants and Inheritance
The useful effect of class invariants in object-oriented software is enhanced in the presence of inheritance. Class invariants are inherited, that is, "the invariants of all the parents of a class apply to the class itself."
Inheritance can allow descendant classes to alter implementation data of parent classes, so it would be possible for a descendant class to change the state of instances in a way that made them invalid from the viewpoint of the parent class. The concern for this type of misbehaving descendant is one reason object-oriented software designers give for favoring composition over inheritance (i.e., inheritance breaks encapsulation).
However, because class invariants are inherited, the class invariant for any particular class consists of any invariant assertions coded immediately on that class, logically "and-ed" with all the invariant clauses inherited from the class's parents. This means that even though descendant classes may have access to the implementation data of the their parents, the class invariant can prevent them from manipulating those data in any way that produces an invalid instance at runtime.
Read more about this topic: Class Invariant
Famous quotes containing the words class and/or inheritance:
“Alas for the cripple Practice when it seeks to come up with the bird Theory, which flies before it. Try your design on the best school. The scholars are of all ages and temperaments and capacities. It is difficult to class them, some are too young, some are slow, some perverse. Each requires so much consideration, that the morning hope of the teacher, of a day of love and progress, is often closed at evening by despair.”
—Ralph Waldo Emerson (18031882)
“Late in the afternoon we passed a man on the shore fishing with a long birch pole.... The characteristics and pursuits of various ages and races of men are always existing in epitome in every neighborhood. The pleasures of my earliest youth have become the inheritance of other men. This man is still a fisher, and belongs to an era in which I myself have lived.”
—Henry David Thoreau (18171862)