Course contentsShow
← Java
Lesson 436 of 2,87010. Inheritance FundamentalsFree lesson

Violating is-a: Common Design Mistakes

Identify inheritance misuse where subclasses don't logically satisfy the is-a relationship.

Violating is-a: Common Design Mistakes

What you'll learn: How to recognize when inheritance is misused and doesn't reflect a true is-a relationship.

The Problem with Inheritance Misuse

Just because you can use extends doesn't mean you should. One of the most common mistakes in object-oriented design is forcing inheritance where the subclass doesn't genuinely satisfy the is-a relationship with its superclass. When you violate this principle, your code becomes confusing, brittle, and prone to bugs.

Classic Examples of Misuse

Square extends Rectangle: At first glance, this seems logical—a square is mathematically a type of rectangle. But consider behavior: a Rectangle lets you set width and height independently. If Square overrides setWidth() to also change height (to keep sides equal), it violates the expected behavior of a rectangle. Code expecting a Rectangle will break when given a Square. This violates substitutability.

Stack extends ArrayList: You might think "a stack uses a list internally, so let's extend it!" But a stack should only allow push/pop operations, while ArrayList exposes get(), set(), and insertion at any index. Extending ArrayList exposes methods that break the stack's contract. A stack has-a list; it doesn't is-a list.

Employee extends Person for code reuse: If you extend just to reuse fields like name and age, but Employee isn't truly substitutable for Person in your system's logic, use composition instead. Inheritance is for polymorphism, not just sharing code.

How to Avoid This Mistake

Ask yourself: "Can I truly substitute the subclass anywhere the superclass is expected without breaking behavior?" If the answer is no, use composition (has-a) instead of inheritance.

Key Takeaway: Only use inheritance when your subclass genuinely is-a specialized version of the superclass and can be substituted without breaking expected behavior—otherwise, you're creating fragile, misleading designs.