Is-A Hierarchies in Action
Part of: Inheritance
Designing with Is-A Inheritance models the is-a relationship : a subclass is a kind of its superclass. A Square is a Shape; a Dog is an Animal. If "X is a Y" sounds natural in English, inheritance is usually the right tool. If it sounds wrong, prefer composition (has-a) instead. Building a Hierarchy This capstone combines everything: extends, super(...), overriding, super.method(), and polymorphism. Consider a shape hierarchy: Notice the chain: Square is a Rectangle, which is a Shape. Square calls super(side, side) to reuse Rectangle's construction, and it inherits area() without rewriting it. Polymorphic Totals Because every subclass is a Shape, you can total their areas uniformly: Dynamic dispatch calls the right area() for each object. This is the payoff of a well-designed is-a hierarchy: general code that works for any specialized type. Substitutability A subclass object can be used anywhere its superclass is expected. This is the Liskov substitution idea: passing a Square where a Shape is required must always be safe. In the final challenge you will read several rectangles, store them in a Shape[], and print the sum of their areas using polymorphism, tying together extends, su
Challenge: Total Area