Code reuse through subtyping Inheritance Basics Code reuse through subtyping
Inheritance : What is It Technical mechanism for code reuse Conceptual design mechanism : is-a relationship
Inheritance Terminology Inheritance : derive a class from another class Terminology Parent or Base class Derived or Child class UML Arrow from derived to parent class
Conceptual Model How to visualize inheritance: Apple consists of a Fruit object and an Apple wrapper Wrapper can add new features / hide existing ones Fruit Apple Other Code
Inheritance Heirarchies Multiple classes can derive from one base Can derive from a class that is derived
Geometric Object Example Function also available in Circle & Rectagle Circle & Rectangle could use toString() but chose to override
Circle Interactions Calls on a derived class handled by code there if possible, otherwise by parent class Geometric Object Circle
Circle Code State inheritance with : public ParentClass Do not redeclare parent members unless overriding them
Using Inherited Members Derived class does NOT have access to private members of parent:
Using Inherited Members Derived class does NOT have access to private members of parent Must use public interface to access
Generic Programming A derived class can be treated as parent type:
Protected Access Private Only accessible in this class
Protected Access Private Only accessible in this class Public Accessible anywhere
Protected Access Private Only accessible in this class Public Accessible anywhere Protected Accessible in this class and any subclasses
Access Summary Private Protected Public Member variables Helper functions no one else should use Protected Member variables it is reasonable for child classes to work with Functions you only want subclasses to use Public Functions Constants