<p>Why prefer composition over inheritance?  What trade-offs are there for each approach?  When should you choose inheritance over composition?</p>

[{'answer_id': 49016, 'author': 'Nick Zalutskiy', 'author_id': 1959, 'author_profile': 'https://Stackoverflow.com/users/1959', 'pm_score': 9, 'selected': False, 'text': '<p>Think of containment as a <strong>has a</strong> relationship. A car &quot;has an&quot; engine, a person &quot;has a&quot; name, etc.</p>\n<p>Think of inheritance as an <strong>is a</strong> relationship. A car &quot;is a&quot; vehicle, a person &quot;is a&quot; mammal, etc.</p>\n<p>I take no credit for this approach. I took it straight from the <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="noreferrer" rel="nofollow noreferrer">Second Edition of Code Complete</a> by <a href="https://stevemcconnell.com/" rel="noreferrer">Steve McConnell</a>, <em>Section 6.3</em>.</p>\n'}, {'answer_id': 49028, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>A rule of thumb I have heard is inheritance should be used when its a "is-a" relationship and composition when its a "has-a". Even with that I feel that you should always lean towards composition because it eliminates a lot of complexity.</p>\n'}, {'answer_id': 49037, 'author': 'dance2die', 'author_id': 4035, 'author_profile': 'https://Stackoverflow.com/users/4035', 'pm_score': 6, 'selected': False, 'text': '<p>In Java or C#, an object cannot change its type once it has been instantiated.</p>\n\n<p>So, if your object need to appear as a different object or behave differently depending on an object state or conditions, then use <strong>Composition</strong>: Refer to <a href="http://www.dofactory.com/Patterns/PatternState.aspx" rel="noreferrer">State</a> and <a href="http://www.dofactory.com/Patterns/PatternStrategy.aspx" rel="noreferrer">Strategy</a> Design Patterns.</p>\n\n<p>If the object need to be of the same type, then use <strong>Inheritance</strong> or implement interfaces.</p>\n'}, {'answer_id': 49041, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 4, 'selected': False, 'text': '<p>Inheritance is very powerful, but you can\'t force it (see: the <a href="http://en.wikipedia.org/wiki/Circle-ellipse_problem" rel="noreferrer">circle-ellipse problem</a>). If you really can\'t be completely sure of a true "is-a" subtype relationship, then it\'s best to go with composition.</p>\n'}, {'answer_id': 49070, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 7, 'selected': False, 'text': "<p>Another, very pragmatic reason, to prefer composition over inheritance has to do with your domain model, and mapping it to a relational database. It's really hard to map inheritance to the SQL model (you end up with all sorts of hacky workarounds, like creating columns that aren't always used, using views, etc). Some ORMLs try to deal with this, but it always gets complicated quickly. Composition can be easily modeled through a foreign-key relationship between two tables, but inheritance is much harder.</p>\n"}, {'answer_id': 49090, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 3, 'selected': False, 'text': '<p>Aside from is a/has a considerations, one must also consider the "depth" of inheritance your object has to go through. Anything beyond five or six levels of inheritance deep might cause unexpected casting and boxing/unboxing problems, and in those cases it might be wise to compose your object instead.</p>\n'}, {'answer_id': 53354, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 10, 'selected': False, 'text': '<p><em>Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach.</em> With composition, it\'s easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.</p>\n\n<p>My acid test for the above is:  </p>\n\n<ul>\n<li><p>Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates <strong>Inheritance</strong>. </p>\n\n<ul>\n<li>e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane. </li>\n</ul></li>\n<li><p>Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for <strong>Composition.</strong>   </p>\n\n<ul>\n<li>e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.</li>\n</ul></li>\n</ul>\n\n<p><strong>Update:</strong> Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov\'s <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov Substitution Principle</a> as a test for \'Should I be inheriting from this type?\'</p>\n'}, {'answer_id': 832554, 'author': 'Anzurio', 'author_id': 99635, 'author_profile': 'https://Stackoverflow.com/users/99635', 'pm_score': 3, 'selected': False, 'text': '<p>When you want to "copy"/Expose the base class\' API, you use inheritance. When you only want to "copy" functionality, use delegation.</p>\n\n<p>One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn\'t use inheritance given that you don\'t want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.</p>\n'}, {'answer_id': 842089, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 7, 'selected': False, 'text': '<p>While in short words I would agree with "Prefer composition over inheritance", very often for me it sounds like "prefer potatoes over coca-cola". There are places for inheritance and places for composition. You need to understand difference, then this question will disappear. What it really means for me is "if you are going to use inheritance - think again, chances are you need composition".</p>\n\n<p>You should prefer potatoes over coca cola when you want to eat, and coca cola over potatoes when you want to drink.</p>\n\n<p>Creating a subclass should mean more than just a convenient way to call superclass methods. You should use inheritance when subclass "is-a" super class both structurally and functionally, when it can be used as superclass and you are going to use that. If it is not the case - it is not inheritance, but something else. Composition is when your objects consists of another, or has some relationship to them.</p>\n\n<p>So for me it looks like if someone does not know if he needs inheritance or composition, the real problem is that he does not know if he want to drink or to eat. Think about your problem domain more, understand it better.</p>\n'}, {'answer_id': 891820, 'author': 'aleemb', 'author_id': 50475, 'author_profile': 'https://Stackoverflow.com/users/50475', 'pm_score': 8, 'selected': False, 'text': "<p>If you understand the difference, it's easier to explain.</p>\n<h2>Procedural Code</h2>\n<p>An example of this is PHP without the use of classes (particularly before PHP5). All logic is encoded in a set of functions. You may include other files containing helper functions and so on and conduct your business logic by passing data around in functions. This can be very hard to manage as the application grows. PHP5 tries to remedy this by offering a more object-oriented design.</p>\n<h2>Inheritance</h2>\n<p>This encourages the use of classes. Inheritance is one of the three tenets of OO design (inheritance, polymorphism, encapsulation).</p>\n<pre><code>class Person {\n   String Title;\n   String Name;\n   Int Age\n}\n\nclass Employee : Person {\n   Int Salary;\n   String Title;\n}\n</code></pre>\n<p>This is inheritance at work. The <code>Employee</code> &quot;<strong>is a</strong>&quot; <code>Person</code> or inherits from <code>Person</code>. All inheritance relationships are &quot;is-a&quot; relationships. <code>Employee</code> also shadows the <code>Title</code> property from <code>Person</code>, meaning <code>Employee.Title</code> will return the <code>Title</code> for the <code>Employee</code> and not the <code>Person</code>.</p>\n<h2>Composition</h2>\n<p>Composition is favoured over inheritance. To put it very simply you would have:</p>\n<pre><code>class Person {\n   String Title;\n   String Name;\n   Int Age;\n\n   public Person(String title, String name, String age) {\n      this.Title = title;\n      this.Name = name;\n      this.Age = age;\n   }\n\n}\n\nclass Employee {\n   Int Salary;\n   private Person person;\n\n   public Employee(Person p, Int salary) {\n       this.person = p;\n       this.Salary = salary;\n   }\n}\n\nPerson johnny = new Person (&quot;Mr.&quot;, &quot;John&quot;, 25);\nEmployee john = new Employee (johnny, 50000);\n</code></pre>\n<p>Composition is typically &quot;<strong>has a</strong>&quot; or &quot;<strong>uses a</strong>&quot; relationship. Here the <code>Employee</code> class has a <code>Person</code>. It does not inherit from <code>Person</code> but instead gets the <code>Person</code> object passed to it, which is why it &quot;has a&quot; Person.</p>\n<h2>Composition over Inheritance</h2>\n<p>Now say you want to create a <code>Manager</code> type so you end up with:</p>\n<pre><code>class Manager : Person, Employee {\n   ...\n}\n</code></pre>\n<p>This example will work fine, however, what if <code>Person</code> and <code>Employee</code> both declared <code>Title</code>? Should <code>Manager.Title</code> return &quot;Manager of Operations&quot; or &quot;Mr.&quot;? Under composition this ambiguity is better handled:</p>\n<pre><code>Class Manager {\n   public string Title;\n   public Manager(Person p, Employee e)\n   {\n      this.Title = e.Title;\n   }\n}\n</code></pre>\n<p>The <code>Manager</code> object is composed of an <code>Employee</code> and a <code>Person</code>. The <code>Title</code> behaviour is taken from <code>Employee</code>. This explicit composition removes ambiguity among other things and you'll encounter fewer bugs.</p>\n"}, {'answer_id': 891854, 'author': 'egaga', 'author_id': 103014, 'author_profile': 'https://Stackoverflow.com/users/103014', 'pm_score': 4, 'selected': False, 'text': "<p>Inheritance creates a strong relationship between a subclass and super class; subclass must be aware of super class'es implementation details. Creating the super class is much harder, when you have to think about how it can be extended. You have to document class invariants carefully, and state what other methods overridable methods use internally. </p>\n\n<p>Inheritance is sometimes useful, if the hierarchy really represents a is-a-relationship. It relates to Open-Closed Principle, which states that classes should be closed for modification but open to extension. That way you can have polymorphism; to have a generic method that deals with super type and its methods, but via dynamic dispatch the method of subclass is invoked. This is flexible, and helps to create indirection, which is essential in software (to know less about implementation details).</p>\n\n<p>Inheritance is easily overused, though, and creates additional complexity, with hard dependencies between classes. Also understanding what happens during execution of a program gets pretty hard due to layers and dynamic selection of method calls.</p>\n\n<p>I would suggest using composing as the default. It is more modular, and gives the benefit of late binding (you can change the component dynamically). Also it's easier to test the things separately. And if you need to use a method from a class, you are not forced to be of certain form (Liskov Substitution Principle).</p>\n"}, {'answer_id': 891908, 'author': 'Ahmed', 'author_id': 70289, 'author_profile': 'https://Stackoverflow.com/users/70289', 'pm_score': 8, 'selected': False, 'text': "<p>With all the undeniable benefits provided by inheritance, here's some of its disadvantages.</p>\n\n<p><strong>Disadvantages of Inheritance:</strong></p>\n\n<ol>\n<li>You can't change the implementation inherited from super classes at runtime (obviously because inheritance is defined at compile time).</li>\n<li>Inheritance exposes a subclass to details of its parent class implementation, that's why it's often said that inheritance breaks encapsulation (in a sense that you really need to focus on interfaces only not implementation, so reusing by sub classing is not always preferred).</li>\n<li>The tight coupling provided by inheritance makes the implementation of a subclass very bound up with the implementation of a super class that any change in the parent implementation will force the sub class to change.</li>\n<li>Excessive reusing by sub-classing can make the inheritance stack very deep and very confusing too.</li>\n</ol>\n\n<p>On the other hand <b>Object composition</b> is defined at runtime through objects acquiring references to other objects. In such a case these objects will never be able to reach each-other's protected data (no encapsulation break) and will be forced to respect each other's interface. And in this case also, implementation dependencies will be a lot less than in case of inheritance.</p>\n"}, {'answer_id': 1020959, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>What do you want to force yourself (or another programmer) to adhere to and when do you want to allow yourself (or another programmer) more freedom. It has been argued that inheritance is helpful when you want to force someone into a way of dealing with/solving a particular problem so they can't head off in the wrong direction.</p>\n\n<p><code>Is-a</code> and <code>Has-a</code> is a helpful rule of thumb.</p>\n"}, {'answer_id': 2124476, 'author': 'Mike Valenty', 'author_id': 124839, 'author_profile': 'https://Stackoverflow.com/users/124839', 'pm_score': 6, 'selected': False, 'text': '<p>Inheritance is pretty enticing especially coming from procedural-land and it often looks deceptively elegant. I mean all I need to do is add this one bit of functionality to some other class, right? Well, one of the problems is that <h2>inheritance is probably the worst form of coupling you can have</h2></p>\n\n<p>Your base class breaks encapsulation by exposing implementation details to subclasses in the form of protected members. This makes your system rigid and fragile. The more tragic flaw however is the new subclass brings with it all the baggage and opinion of the inheritance chain.</p>\n\n<p>The article, <a href="http://www.agileatwork.com/inheritance-is-evil-the-story-of-the-epic-fail-of-dataannotationsmodelbinder/" rel="noreferrer">Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder</a>, walks through an example of this in C#. It shows the use of inheritance when composition should have been used and how it could be refactored.</p>\n'}, {'answer_id': 3863382, 'author': 'nabeelfarid', 'author_id': 288746, 'author_profile': 'https://Stackoverflow.com/users/288746', 'pm_score': 4, 'selected': False, 'text': '<p>You need to have a look at <strong><a href="http://web.archive.org/web/20110722014513/http://www.objectmentor.com/resources/articles/lsp.pdf" rel="noreferrer">The Liskov Substitution Principle</a></strong> in Uncle Bob\'s <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="noreferrer">SOLID</a> principles of class design. :) </p>\n'}, {'answer_id': 4303034, 'author': 'simplfuzz', 'author_id': 49560, 'author_profile': 'https://Stackoverflow.com/users/49560', 'pm_score': 4, 'selected': False, 'text': "<p>Suppose an aircraft has only two parts: an engine and wings.<br>\nThen there are two ways to design an aircraft class.  </p>\n\n<pre><code>Class Aircraft extends Engine{\n  var wings;\n}\n</code></pre>\n\n<p>Now your aircraft can start with having fixed wings<br>\nand change them to rotary wings on the fly. It's essentially<br>\nan engine with wings. But what if I wanted to change<br>\nthe engine on the fly as well?  </p>\n\n<p>Either the base class <code>Engine</code> exposes a mutator to change its<br>\nproperties, or I redesign <code>Aircraft</code> as:   </p>\n\n<pre><code>Class Aircraft {\n  var wings;\n  var engine;\n}\n</code></pre>\n\n<p>Now, I can replace my engine on the fly as well.</p>\n"}, {'answer_id': 8353160, 'author': 'Shelby Moore III', 'author_id': 615784, 'author_profile': 'https://Stackoverflow.com/users/615784', 'pm_score': 2, 'selected': False, 'text': '<p>Subtyping is appropriate and more powerful where the <a href="https://stackoverflow.com/a/8352969">invariants can be enumerated</a>, else use function composition for extensibility.</p>\n'}, {'answer_id': 8413988, 'author': 'Parag', 'author_id': 34956, 'author_profile': 'https://Stackoverflow.com/users/34956', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with @Pavel, when he says, there are places for composition and there are places for inheritance.</p>\n\n<p>I think inheritance should be used if your answer is an affirmative to any of these questions.</p>\n\n<ul>\n<li>Is your class part of a structure that benefits from polymorphism ? For example, if you had a Shape class, which declares a method called draw(), then we clearly need Circle and Square classes to be subclasses of Shape, so that their client classes would depend on Shape and not on specific subclasses.</li>\n<li>Does your class need to re-use any high level interactions defined in another class ? The <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">template method</a> design pattern would be impossible to implement without inheritance. I believe all extensible frameworks use this pattern.</li>\n</ul>\n\n<p>However, if your intention is purely that of code re-use, then composition most likely is a better design choice.</p>\n'}, {'answer_id': 10678768, 'author': 'Peter Tseng', 'author_id': 280783, 'author_profile': 'https://Stackoverflow.com/users/280783', 'pm_score': 5, 'selected': False, 'text': '<p>My general rule of thumb: <em>Before using inheritance, consider if composition makes more sense.</em></p>\n\n<p>Reason: <em>Subclassing usually means more complexity and connectedness, i.e. harder to change, maintain, and scale without making mistakes.</em></p>\n\n<p>A much more complete and concrete <a href="http://www.javalobby.org/forums/thread.jspa?forumID=61&amp;threadID=16487#91822172" rel="noreferrer">answer from Tim Boudreau</a> of Sun:</p>\n\n<blockquote>\n  <p>Common problems to the use of inheritance as I see it are:</p>\n  \n  <ul>\n  <li><em>Innocent acts can have unexpected results</em> - The classic example of this is calls to overridable methods from the superclass\n  constructor, before the subclasses instance fields have been\n  initialized. In a perfect world, nobody would ever do that. This is\n  not a perfect world.</li>\n  <li><em>It offers perverse temptations for subclassers to make assumptions about order of method calls and such</em> - such assumptions tend not to\n  be stable if the superclass may evolve over time. See also <a href="http://www.javalobby.org/forums/thread.jspa?threadID=16036&amp;messageID=91819530#91819530" rel="noreferrer">my toaster\n  and coffee pot analogy</a>.</li>\n  <li><em>Classes get heavier</em> - you don\'t necessarily know what work your superclass is doing in its constructor, or how much memory it\'s going\n  to use. So constructing some innocent would-be lightweight object can\n  be far more expensive than you think, and this may change over time if\n  the superclass evolves</li>\n  <li><em>It encourages an explosion of subclasses</em>. Classloading costs time, more classes costs memory. This may be a non-issue until you\'re\n  dealing with an app on the scale of NetBeans, but there, we had real\n  issues with, for example, menus being slow because the first display\n  of a menu triggered massive class loading. We fixed this by moving to\n  more declarative syntax and other techniques, but that cost time to\n  fix as well.</li>\n  <li><em>It makes it harder to change things later</em> - if you\'ve made a class public, swapping the superclass is going to break subclasses -\n  it\'s a choice which, once you\'ve made the code public, you\'re married\n  to. So if you\'re not altering the real functionality to your\n  superclass, you get much more freedom to change things later if you\n  use, rather than extend the thing you need. Take, for example,\n  subclassing JPanel - this is usually wrong; and if the subclass is\n  public somewhere, you never get a chance to revisit that decision. If\n  it\'s accessed as JComponent getThePanel() , you can still do it (hint:\n  expose models for the components within as your API).</li>\n  <li><em>Object hierarchies don\'t scale (or making them scale later is much harder than planning ahead)</em> - this is the classic "too many layers"\n  problem. I\'ll go into this below, and how the AskTheOracle pattern can\n  solve it (though it may offend OOP purists). </li>\n  </ul>\n  \n  <p>...</p>\n  \n  <p>My take on what to do, if you do allow for inheritance, which you may\n  take with a grain of salt is:</p>\n  \n  <ul>\n  <li>Expose no fields, ever, except constants</li>\n  <li>Methods shall be either abstract or final</li>\n  <li>Call no methods from the superclass constructor</li>\n  </ul>\n  \n  <p>...</p>\n  \n  <p>all of this applies less to small projects than large ones, and less\n  to private classes than public ones</p>\n</blockquote>\n'}, {'answer_id': 11758048, 'author': 'LCJ', 'author_id': 696627, 'author_profile': 'https://Stackoverflow.com/users/696627', 'pm_score': 2, 'selected': False, 'text': '<p>As many people told, I will first start with the check - whether there exists an &quot;is-a&quot; relationship. If it exists I usually check the following:</p>\n<blockquote>\n<p>Whether the base class can be instantiated. That is, whether the base class can be non-abstract.  If it can be non-abstract I usually prefer composition</p>\n</blockquote>\n<p>E.g 1. Accountant <strong>is an</strong> Employee. But I will <strong>not</strong> use inheritance because a Employee object can be instantiated.</p>\n<p>E.g 2. Book <strong>is a</strong> SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritacne. The SellingItem is an <strong>abstract base class (or interface</strong> in C#)</p>\n<p>What do you think about this approach?</p>\n<p>Also, I support @anon answer in <a href="https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1">Why use inheritance at all?</a></p>\n<blockquote>\n<p>The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don\'t need polymorphism, you probably should not be using inheritance.</p>\n</blockquote>\n<p>@MatthieuM. says in <a href="https://softwareengineering.stackexchange.com/questions/12439/code-smell-inheritance-abuse/12448#comment303759_12448">https://softwareengineering.stackexchange.com/questions/12439/code-smell-inheritance-abuse/12448#comment303759_12448</a></p>\n<blockquote>\n<p>The issue with inheritance is that it can be used for two orthogonal purposes:</p>\n<p>interface (for polymorphism)</p>\n<p>implementation (for code reuse)</p>\n</blockquote>\n<p><strong>REFERENCE</strong></p>\n<ol>\n<li><a href="https://stackoverflow.com/questions/38820/which-class-design-is-better?lq=1">Which class design is better?</a></li>\n<li><a href="https://stackoverflow.com/questions/269496/inheritance-vs-aggregation/269553#comment15610225_269553">Inheritance vs. Aggregation</a></li>\n</ol>\n'}, {'answer_id': 14633709, 'author': 'Mecki', 'author_id': 15809, 'author_profile': 'https://Stackoverflow.com/users/15809', 'pm_score': 5, 'selected': False, 'text': '<p>Personally I learned to always prefer composition over inheritance. There is no programmatic problem you can solve with inheritance which you cannot solve with composition; though you may have to use Interfaces(Java) or Protocols(Obj-C) in some cases. Since C++ doesn\'t know any such thing, you\'ll have to use abstract base classes, which means you cannot get entirely rid of inheritance in C++.</p>\n\n<p>Composition is often more logical, it provides better abstraction, better encapsulation, better code reuse (especially in very large projects) and is less likely to break anything at a distance just because you made an isolated change anywhere in your code. It also makes it easier to uphold the "<em>Single Responsibility Principle</em>", which is often summarized as "<em>There should never be more than one reason for a class to change.</em>", and it means that every class exists for a specific purpose and it should only have methods that are directly related to its purpose. Also having a very shallow inheritance tree makes it much easier to keep the overview even when your project starts to get really large. Many people think that inheritance represents our <em>real world</em> pretty well, but that isn\'t the truth. The real world uses much more composition than inheritance. Pretty much every real world object you can hold in your hand has been composed out of other, smaller real world objects.</p>\n\n<p>There are downsides of composition, though. If you skip inheritance altogether and only focus on composition, you will notice that you often have to write a couple of extra code lines that weren\'t necessary if you had used inheritance. You are also sometimes forced to repeat yourself and this violates the <em>DRY Principle</em> (DRY = Don\'t Repeat Yourself). Also composition often requires delegation, and a method is just calling another method of another object with no other code surrounding this call. Such "double method calls" (which may easily extend to triple or quadruple method calls and even farther than that) have much worse performance than inheritance, where you simply inherit a method of your parent. Calling an inherited method may be equally fast as calling a non-inherited one, or it may be slightly slower, but is usually still faster than two consecutive method calls.</p>\n\n<p>You may have noticed that most OO languages don\'t allow multiple inheritance. While there are a couple of cases where multiple inheritance can really buy you something, but those are rather exceptions than the rule. Whenever you run into a situation where you think "multiple inheritance would be a really cool feature to solve this problem", you are usually at a point where you should re-think inheritance altogether, since even it may require a couple of extra code lines, a solution based on composition will usually turn out to be much more elegant, flexible and future proof.</p>\n\n<p>Inheritance is really a cool feature, but I\'m afraid it has been overused the last couple of years. People treated inheritance as the one hammer that can nail it all, regardless if it was actually a nail, a screw, or maybe a something completely different.</p>\n'}, {'answer_id': 16046223, 'author': 'Tero Tolonen', 'author_id': 2287682, 'author_profile': 'https://Stackoverflow.com/users/2287682', 'pm_score': 3, 'selected': False, 'text': '<p>These two ways can live together just fine and actually support each other.</p>\n\n<p>Composition is just playing it modular: you create interface similar to the parent class, create new object and delegate calls to it. If these objects need not to know of each other, it\'s quite safe and easy to use composition. There are so many possibilites here.</p>\n\n<p>However, if the parent class for some reason needs to access functions provided by the "child class" for inexperienced programmer it may look like it\'s a great place to use  inheritance. The parent class can just call it\'s own abstract "foo()" which is overwritten by the subclass and then it can give the value to the abstract base.</p>\n\n<p>It looks like a nice idea, but in many cases it\'s better just give the class an object which implements the foo() (or even set the value provided the foo() manually) than to inherit the new class from some base class which requires the function foo() to be specified.</p>\n\n<p>Why?</p>\n\n<p><strong>Because inheritance is a poor way of moving information</strong>.</p>\n\n<p>The composition has a real edge here: the relationship can be reversed: the "parent class" or "abstract worker" can aggregate any specific "child" objects implementing certain interface + <strong>any child can be set inside any other type of parent, which accepts it\'s type</strong>. And there can be any number of objects, for example MergeSort or QuickSort could sort any list of objects implementing an abstract Compare -interface. Or to put it another way: any group of objects which implement "foo()" and other group of objects which can make use of objects having "foo()" can play together. </p>\n\n<p>I can think of three real reasons for using inheritance:</p>\n\n<ol>\n<li>You have many classes with <strong>same interface</strong> and you want to save time writing them</li>\n<li>You have to use same Base Class for each object</li>\n<li>You need to modify the private variables, which can not be public in any case</li>\n</ol>\n\n<p>If these are true, then it is probably necessary to use inheritance.</p>\n\n<p>There is nothing bad in using reason 1, it is very good thing to have a solid interface on your objects. This can be done using composition or with inheritance, no problem - if this interface is simple and does not change. Usually inheritance is quite effective here.</p>\n\n<p>If the reason is number 2 it gets a bit tricky. Do you really only need to use the same base class? In general, just using the same base class is not good enough, but it may be a requirement of your framework, a design consideration which can not be avoided.</p>\n\n<p>However, if you want to use the private variables, the case 3, then you may be in trouble. <strong>If you consider global variables unsafe, then you should consider using inheritance to get access to private variables also unsafe</strong>. Mind you, global variables are not all THAT bad - databases are essentially big set of global variables. But if you can handle it, then it\'s quite fine.</p>\n'}, {'answer_id': 18548784, 'author': 'Enrique Molinari', 'author_id': 842533, 'author_profile': 'https://Stackoverflow.com/users/842533', 'pm_score': 2, 'selected': False, 'text': '<p>Inheritance is a very powerfull machanism for code reuse. But needs to be used properly. I would say that inheritance is used correctly if the subclass is also a subtype of the parent class. As mentioned above, the Liskov Substitution Principle is the key point here. </p>\n\n<p>Subclass is not the same as subtype. You might create subclasses that are not subtypes (and this is when you should use composition). To understand what a subtype is, lets start giving an explanation of what a type is.</p>\n\n<p>When we say that the number 5 is of type integer, we are stating that 5 belongs to a set of possible values (as an example, see the possible values for the Java primitive types). We are also stating that there is a valid set of methods I can perform on the value like addition and subtraction. And finally we are stating that there are a set of properties that are always satisfied, for example, if I add the values 3 and 5, I will get 8 as a result.</p>\n\n<p>To give another example, think about the abstract data types, Set of integers and List of integers, the values they can hold are restricted to integers. They both support a set of methods, like add(newValue) and size(). And they both have different properties (class invariant), Sets does not allow duplicates while List does allow duplicates (of course there are other properties that they both satisfy).</p>\n\n<p>Subtype is also a type, which has a relation to another type, called parent type (or supertype). The subtype must satisfy the features (values, methods and properties) of the parent type. The relation means that in any context where the supertype is expected, it can be substitutable by a subtype, without affecting the behaviour of the execution. Let’s go to see some code to exemplify what I’m saying. Suppose I write a List of integers (in some sort of pseudo language):</p>\n\n<pre><code>class List {\n  data = new Array();\n\n  Integer size() {\n    return data.length;\n  }\n\n  add(Integer anInteger) {\n    data[data.length] = anInteger;\n  }\n}\n</code></pre>\n\n<p>Then, I write the Set of integers as a subclass of the List of integers:</p>\n\n<pre><code>class Set, inheriting from: List {\n  add(Integer anInteger) {\n     if (data.notContains(anInteger)) {\n       super.add(anInteger);\n     }\n  }\n}\n</code></pre>\n\n<p>Our Set of integers class is a subclass of List of Integers, but is not a subtype, due to it is not satisfying all the features of the List class. The values, and the signature of the methods are satisfied but the properties are not. The behaviour of the add(Integer) method has been clearly changed, not preserving the properties of the parent type. Think from the point of view of the client of your classes. They might receive a Set of integers where a List of integers is expected. The client might want to add a value and get that value added to the List even if that value already exist in the List. But her wont get that behaviour if the value exists. A big suprise for her!</p>\n\n<p>This is a classic example of an improper use of inheritance. Use composition in this case.</p>\n\n<p>(a fragment from: <a href="http://www.copypasteisforword.com/notes/use-inheritance-properly" rel="nofollow">use inheritance properly</a>).</p>\n'}, {'answer_id': 20832301, 'author': 'Amir Aslam', 'author_id': 1505065, 'author_profile': 'https://Stackoverflow.com/users/1505065', 'pm_score': 3, 'selected': False, 'text': '<p>When you have an <strong>is-a</strong> relation between two classes (example dog is a canine), you go for inheritance.</p>\n\n<p>On the other hand when you have <strong>has-a</strong> or some adjective relationship between two classes (student has courses) or (teacher studies courses), you chose composition.</p>\n'}, {'answer_id': 20921914, 'author': 'luke1985', 'author_id': 2000185, 'author_profile': 'https://Stackoverflow.com/users/2000185', 'pm_score': 1, 'selected': False, 'text': '<p>This rule is a complete nonsense. Why? </p>\n\n<p>The reason is that in every case it is possible to tell whether to use composition or inheritance. \nThis is determined by the answer to a question: "IS something A something else" or "HAS \nsomething A something else". </p>\n\n<p>You cannot "prefer" to make something to be something else or to have something else. Strict logical rules apply. </p>\n\n<p>Also there are no "contrived examples" because in every situation an answer to this question can be given. </p>\n\n<p>If you cannot answer this question there is something else wrong. \nThis includes\noverlapping responsibilities of classess which are usually the result of <a href="http://devmatrix.wordpress.com/wp-admin/post.php?post=115&amp;action=edit&amp;message=6&amp;postpost=v2" rel="nofollow">wrong use of interfaces</a>, less often by rewriting same code in different classess. </p>\n\n<p>To avoid this situations I also recommend to use good names for classes , that fully resemble their responsibilities. </p>\n'}, {'answer_id': 22475358, 'author': 'Shami Qureshi', 'author_id': 3274044, 'author_profile': 'https://Stackoverflow.com/users/3274044', 'pm_score': 2, 'selected': False, 'text': '<p>Composition v/s Inheritance is a wide subject. There is no real answer for what is better as I think it all depends on the design of the system.</p>\n\n<p>Generally type of relationship between object provide better information to choose one of them.</p>\n\n<p>If relation type is  "IS-A" relation then Inheritance is better approach.\notherwise relation type is  "HAS-A" relation then composition will better approach.</p>\n\n<p>Its totally depend on entity relationship.</p>\n'}, {'answer_id': 24036352, 'author': 'Yash Sampat', 'author_id': 3287204, 'author_profile': 'https://Stackoverflow.com/users/3287204', 'pm_score': 3, 'selected': False, 'text': "<p>A simple way to make sense of this would be that inheritance should be used when you need an object of your class to have the same <em>interface</em> as its parent class, so that it can thereby be treated as an object of the parent class (upcasting). Moreover, function calls on a derived class object would remain the same everywhere in code, but the specific method to call would be determined at runtime (i.e. the low-level <em>implementation</em> differs, the high-level <em>interface</em> remains the same).</p>\n\n<p>Composition should be used when you do not need the new class to have the same interface, i.e. you wish to conceal certain aspects of the class' implementation which the user of that class need not know about. So composition is more in the way of supporting <em>encapsulation</em> (i.e. concealing the implementation) while inheritance is meant to support <em>abstraction</em> (i.e. providing a simplified representation of something, in this case the <strong>same</strong> interface for a range of types with different internals).</p>\n"}, {'answer_id': 29675042, 'author': 'Veverke', 'author_id': 1219280, 'author_profile': 'https://Stackoverflow.com/users/1219280', 'pm_score': 2, 'selected': False, 'text': '<p>I see no one mentioned the <a href="http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem" rel="nofollow"><strong>diamond problem</strong></a>, which might arise with inheritance. </p>\n\n<p>In a glance, if classes B and C inherit A and both override method X, and a fourth class D, inherits from both B and C, and does not override X, which implementation of X D is supposed to use?</p>\n\n<p><a href="http://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow">Wikipedia</a> offers a nice overview of the topic being discussed in this question.</p>\n'}, {'answer_id': 32557773, 'author': 'lcn', 'author_id': 2073130, 'author_profile': 'https://Stackoverflow.com/users/2073130', 'pm_score': 6, 'selected': False, 'text': '<p>Didn\'t find a satisfactory answer here, so I wrote a new one.</p>\n\n<p>To understand why "<em>prefer</em> composition over inheritance", we need first get back the assumption omitted in this shortened idiom.</p>\n\n<p>There are two benefits of inheritance: <a href="https://www.cs.princeton.edu/courses/archive/fall98/cs441/mainus/node12.html" rel="noreferrer">subtyping and subclassing</a></p>\n\n<ol>\n<li><p><strong>Subtyping</strong> means conforming to a type (interface) signature, i.e. a set of APIs, and one can override part of the signature to achieve subtyping polymorphism.</p></li>\n<li><p><strong>Subclassing</strong> means implicit reuse of method implementations.</p></li>\n</ol>\n\n<p>With the two benefits comes two different purposes for doing inheritance: subtyping oriented and code reuse oriented.</p>\n\n<p>If code reuse is the <em>sole</em> purpose, subclassing may give one more than what he needs, i.e. some public methods of the parent class don\'t make much sense for the child class. In this case, instead of favoring composition over inheritance, composition is <em>demanded</em>. This is also where the "is-a" vs. "has-a" notion comes from.</p>\n\n<p>So only when subtyping is purposed, i.e. to use the new class later in a polymorphic manner, do we face the problem of choosing inheritance or composition. This is the assumption that gets omitted in the shortened idiom under discussion.</p>\n\n<p>To subtype is to conform to a type signature, this means composition has always to expose no less amount of APIs of the type. Now the trade offs kick in:</p>\n\n<ol>\n<li><p>Inheritance provides straightforward code reuse if not overridden, while composition has to re-code every API, even if it\'s just a simple job of delegation.</p></li>\n<li><p>Inheritance provides straightforward <a href="https://en.wikipedia.org/wiki/This_%28computer_programming%29#Open_recursion" rel="noreferrer">open recursion</a> via the internal polymorphic site <code>this</code>, i.e. invoking overriding method (or even <a href="http://www.scala-lang.org/old/node/1637.html#comment-5489" rel="noreferrer">type</a>) in another member function, either public or private (though <a href="https://softwareengineering.stackexchange.com/questions/35946/is-it-bad-code-smell-if-private-method-calls-public-one">discouraged</a>). Open recursion can be <a href="https://github.com/akottr/edu-pattern/blob/master/org.akottr.patterns.composition/src/org/akottr/patterns/composition/inheritance/Compositon.java" rel="noreferrer">simulated via composition</a>, but it requires extra effort and may not always viable(?). This <a href="https://stackoverflow.com/a/2238735/2073130">answer</a> to a duplicated question talks something similar.</p></li>\n<li><p>Inheritance exposes <em>protected</em> members. This breaks encapsulation of the parent class, and if used by subclass, another dependency between the child and its parent is introduced.</p></li>\n<li><p>Composition has the befit of inversion of control, and its dependency can be injected dynamically, as is shown in <a href="https://en.wikipedia.org/wiki/Decorator_pattern#Java" rel="noreferrer">decorator pattern</a> and <a href="https://en.wikipedia.org/wiki/Proxy_pattern#Java" rel="noreferrer">proxy pattern</a>.</p></li>\n<li><p>Composition has the benefit of <a href="http://www.codecommit.com/blog/scala/the-magic-behind-parser-combinators" rel="noreferrer">combinator-oriented</a> programming, i.e. working in a way like the <a href="https://en.wikipedia.org/wiki/Composite_pattern#Java" rel="noreferrer">composite pattern</a>.</p></li>\n<li><p>Composition immediately follows <a href="https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface">programming to an interface</a>.</p></li>\n<li><p>Composition has the benefit of easy <a href="https://stackoverflow.com/questions/3556652/how-do-java-interfaces-simulate-multiple-inheritance">multiple inheritance</a>.</p></li>\n</ol>\n\n<p>With the above trade offs in mind, we hence <em>prefer</em> composition over inheritance. Yet for tightly related classes, i.e. when implicit code reuse really make benefits, or the magic power of open recursion is desired, inheritance shall be the choice.</p>\n'}, {'answer_id': 37218825, 'author': 'Scott Hannen', 'author_id': 5101046, 'author_profile': 'https://Stackoverflow.com/users/5101046', 'pm_score': 3, 'selected': False, 'text': '<p>To address this question from a different perspective for newer programmers:</p>\n\n<p>Inheritance is often taught early when we learn object-oriented programming, so it\'s seen as an easy solution to a common problem. </p>\n\n<blockquote>\n  <p>I have three classes that all need some common functionality. So if I\n  write a base class and have them all inherit from it, then they will\n  all have that functionality and I\'ll only need to maintain it in once\n  place.</p>\n</blockquote>\n\n<p>It sounds great, but in practice it almost never, ever works, for one of several reasons:  </p>\n\n<ul>\n<li>We discover that there are some other functions that we want our classes to have. If the way that we add functionality to classes is through inheritance, we have to decide - do we add it to the existing base class, even though not every class that inherits from it needs that functionality? Do we create another base class? But what about classes that already inherit from the other base class?</li>\n<li>We discover that for just one of the classes that inherits from our base class we want the base class to behave a little differently. So now we go back and tinker with our base class, maybe adding some virtual methods, or even worse, some code that says, "If I\'m inherited type A, do this, but if I\'m inherited type B, do that." That\'s bad for lots of reasons. One is that every time we change the base class, we\'re effectively changing every inherited class. So we\'re really changing class A, B, C, and D because we need a slightly different behavior in class A. As careful as we think we are, we might break one of those classes for reasons that have nothing to do with those classes.</li>\n<li>We might know why we decided to make all of these classes inherit from each other, but it might not (probably won\'t) make sense to someone else who has to maintain our code. We might force them into a difficult choice - do I do something really ugly and messy to make the change I need (see the previous bullet point) or do I just rewrite a bunch of this.</li>\n</ul>\n\n<p>In the end, we tie our code in some difficult knots and get no benefit whatsoever from it except that we get to say, "Cool, I learned about inheritance and now I used it." That\'s not meant to be condescending because we\'ve all done it. But we all did it because no one told us not to. </p>\n\n<p>As soon as someone explained "favor composition over inheritance" to me, I thought back over every time I tried to share functionality between classes using inheritance and realized that most of the time it didn\'t really work well.</p>\n\n<p>The antidote is the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">Single Responsibility Principle</a>. Think of it as a constraint. My class <em>must</em> do one thing. I <em>must</em> be able to give my class a name that somehow describes that one thing it does. (There are exceptions to everything, but absolute rules are sometimes better when we\'re learning.) It follows that I cannot write a base class called <code>ObjectBaseThatContainsVariousFunctionsNeededByDifferentClasses</code>. Whatever distinct functionality I need must be in its own class, and then other classes that need that functionality can depend on that class, <em>not</em> inherit from it.</p>\n\n<p>At the risk of oversimplifying, that\'s composition - composing multiple classes to work together. And once we form that habit we find that it\'s much more flexible, maintainable, and testable than using inheritance.</p>\n'}, {'answer_id': 37624298, 'author': 'Boris Dalstein', 'author_id': 1951907, 'author_profile': 'https://Stackoverflow.com/users/1951907', 'pm_score': 6, 'selected': False, 'text': '<h1>When can you use composition?</h1>\n<p>You can always use composition. In some cases, inheritance is also possible and may lead to a more powerful and/or intuitive API, but composition is always an option.</p>\n<h1>When can you use inheritance?</h1>\n<p>It is often said that if &quot;a bar is a foo&quot;, then the class <code>Bar</code> can inherit the class <code>Foo</code>. Unfortunately, this test alone is not reliable, use the following instead:</p>\n<blockquote>\n<ol>\n<li>a bar is a foo, <strong>AND</strong></li>\n<li>bars can do everything that foos can do.</li>\n</ol>\n</blockquote>\n<p>The first test ensures that all <em>getters</em> of <code>Foo</code> make sense in <code>Bar</code> (= shared properties), while the second test makes sure that all <em>setters</em> of <code>Foo</code> make sense in <code>Bar</code> (= shared functionality).</p>\n<p><strong>Example: Dog/Animal</strong></p>\n<p>A dog is an animal AND dogs can do everything that animals can do (such as breathing, moving, etc.). Therefore, the class <code>Dog</code> <strong>can</strong> inherit the class <code>Animal</code>.</p>\n<p><strong>Counter-example: Circle/Ellipse</strong></p>\n<p>A circle is an ellipse BUT circles can\'t do everything that ellipses can do. For example, circles can\'t stretch, while ellipses can. Therefore, the class <code>Circle</code> <strong>cannot</strong> inherit the class <code>Ellipse</code>.</p>\n<p>This is called the <a href="https://en.wikipedia.org/wiki/Circle-ellipse_problem" rel="noreferrer">Circle-Ellipse problem</a>, which isn\'t really a problem, but more an indication that &quot;a bar is a foo&quot; isn\'t a reliable test by itself. In particular, this example highlights that derived classes should <em>extend</em> the functionality of base classes, never <em>restrict</em> it. Otherwise, the base class couldn\'t be used polymorphically. Adding the test &quot;bars can do everything that foos can do&quot; ensures that polymorphic use is possible, and is equivalent to the <a href="http://web.archive.org/web/20110722014513/http://www.objectmentor.com/resources/articles/lsp.pdf" rel="noreferrer">Liskov Substitution Principle</a>:</p>\n<blockquote>\n<p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it</p>\n</blockquote>\n<h1>When should you use inheritance?</h1>\n<p>Even if you <em>can</em> use inheritance doesn\'t mean you <em>should</em>: using composition is always an option. Inheritance is a powerful tool allowing implicit code reuse and dynamic dispatch, but it does come with a few disadvantages, which is why composition is often preferred. The trade-offs between inheritance and composition aren\'t obvious, and in my opinion are best explained in <a href="https://stackoverflow.com/a/32557773/1951907">lcn\'s answer</a>.</p>\n<p>As a rule of thumb, I tend to choose inheritance over composition when polymorphic use is expected to be very common, in which case the power of dynamic dispatch can lead to a much more readable and elegant API. For example, having a polymorphic class <code>Widget</code> in GUI frameworks, or a polymorphic class <code>Node</code> in XML libraries allows to have an API which is much more readable and intuitive to use than what you would have with a solution purely based on composition.</p>\n'}, {'answer_id': 39635299, 'author': 'Ravindra babu', 'author_id': 4999394, 'author_profile': 'https://Stackoverflow.com/users/4999394', 'pm_score': 2, 'selected': False, 'text': '<p>Even though Composition is preferred, I would like to highlight pros of <em>Inheritance</em> and cons of <em>Composition</em>.</p>\n\n<p><strong><em>Pros of Inheritance:</em></strong></p>\n\n<ol>\n<li><p>It establishes a logical "<strong>IS A"</strong> relation. If <em>Car</em> and <em>Truck</em> are two types of <em>Vehicle</em> ( base class), child class <strong>IS A</strong> base class. </p>\n\n<p>i.e. </p>\n\n<p><em>Car is a Vehicle</em></p>\n\n<p><em>Truck is a Vehicle</em></p></li>\n<li><p>With inheritance, you can define/modify/extend a capability</p>\n\n<ol>\n<li>Base class provides no implementation and sub-class has to override complete method (abstract) => <strong><em>You can implement a contract</em></strong></li>\n<li>Base class provides default implementation and sub-class can change the behaviour => <strong><em>You can re-define contract</em></strong></li>\n<li>Sub-class adds extension to base class implementation by calling super.methodName() as first statement => <strong><em>You can extend a contract</em></strong></li>\n<li>Base class defines structure of the algorithm  and sub-class will override a part of algorithm => <strong><em>You can implement <a href="https://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">Template_method</a> without change in base class skeleton</em></strong></li>\n</ol></li>\n</ol>\n\n<p><strong><em>Cons of Composition:</em></strong></p>\n\n<ol>\n<li>In inheritance, subclass can directly invoke base class method even though it\'s not implementing base class method because of <strong><em>IS A</em></strong> relation. If you use composition, you have to add methods in container class to expose contained class API</li>\n</ol>\n\n<p>e.g. If  <em>Car</em> contains <em>Vehicle</em> and if you have to get price of the <em>Car</em>, which has been defined in <em>Vehicle</em>, your code will be like this</p>\n\n<pre><code>class Vehicle{\n     protected double getPrice(){\n          // return price\n     }\n} \n\nclass Car{\n     Vehicle vehicle;\n     protected double getPrice(){\n          return vehicle.getPrice();\n     }\n} \n</code></pre>\n'}, {'answer_id': 71568176, 'author': 'Scotty Jamison', 'author_id': 7696223, 'author_profile': 'https://Stackoverflow.com/users/7696223', 'pm_score': 4, 'selected': False, 'text': '<p>If you want the canonical, textbook answer people have been giving since the rise of OOP (which you see many people giving in these answers), then apply the following rule: &quot;if you have an is-a relationship, use inheritance. If you have a has-a relationship, use composition&quot;.</p>\n<p>This is the traditional advice, and if that satisfies you, you can stop reading here and go on your merry way. For everyone else...</p>\n<h1>is-a/has-a comparisons have problems</h1>\n<p>For example:</p>\n<ul>\n<li>A square is-a rectangle, but if your rectangle class has <code>setWidth()</code>/<code>setHeight()</code> methods, then there\'s no reasonable way to make a <code>Square</code> inherit from <code>Rectangle</code> without breaking <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">Liskov\'s substitution principle</a>.</li>\n<li>An is-a relationship can often be rephrased to sound like a has-a relationship. For example, an employee is-a person, but a person also has-an employment status of &quot;employed&quot;.</li>\n<li>is-a relationships can lead to nasty multiple inheritance hierarchies if you\'re not careful. After all, there\'s no rule in English that states that an object <em>is</em> exactly one thing.</li>\n<li>People are quick to pass this &quot;rule&quot; around, but has anyone ever tried to back it up, or explain why it\'s a good heuristic to follow? Sure, it fits nicely into the idea that OOP is supposed to model the real world, but that\'s not in-and-of-itself a reason to adopt a principle.</li>\n</ul>\n<p>See <a href="https://stackoverflow.com/questions/453738/inheritance-or-composition-rely-on-is-a-and-has-a">this</a> StackOverflow question for more reading on this subject.</p>\n<p>To know when to use inheritance vs composition, we first need to understand the pros and cons of each.</p>\n<h1>The problems with implementation inheritance</h1>\n<p>Other answers have done a wonderful job at explaining the issues with inheritance, so I\'ll try to not delve into too many details here. But, here\'s a brief list:</p>\n<ul>\n<li>It can be difficult to follow a logic that weaves between base and sub-class methods.</li>\n<li>Carelessly implementing one method in your class by calling another overridable method will cause you to leak implementation details and break encapsulation, as the end-user could override your method and detect when you internally call it. (See &quot;Effective Java&quot; item 18).</li>\n<li>The <a href="https://en.wikipedia.org/wiki/Fragile_base_class" rel="nofollow noreferrer">fragile base problem</a>, which simply states that your end-user\'s code will break if they happen to depend on the leakage of implementation details when you attempt to change them. To make matters worse, most OOP languages allow inheritance by default - API designers who aren\'t proactively preventing people from inheriting from their public classes need to be extra cautious whenever they refactor their base classes. Unfortunately, the fragile base problem is often misunderstood, causing many to not understand what it takes to maintain a class that anyone can inherit from.</li>\n<li>The <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem" rel="nofollow noreferrer">deadly diamond of death</a></li>\n</ul>\n<h1>The problems with composition</h1>\n<ul>\n<li>It can sometimes be a little verbose.</li>\n</ul>\n<p>That\'s it. I\'m serious. This is still a real issue and can sometimes create conflict with the DRY principle, but it\'s generally not that bad, at least compared to the myriad of pitfalls associated with inheritance.</p>\n<h1>When should inheritance be used?</h1>\n<p>Next time you\'re drawing out your fancy UML diagrams for a project (if you do that), and you\'re thinking about adding in some inheritance, please adhere to the following advice: don\'t.</p>\n<p>At least, not yet.</p>\n<p>Inheritance is sold as a tool to achieve polymorphism, but bundled with it is this powerful code-reuse system, that frankly, most code doesn\'t need. The problem is, as soon as you publicly expose your inheritance hierarchy, you\'re locked into this particular style of code-reuse, even if it\'s overkill to solve your particular problem.</p>\n<p>To avoid this, my two cents would be to never expose your base classes publicly.</p>\n<ul>\n<li>If you need polymorphism, use an interface.</li>\n<li>If you need to allow people to customize the behavior of your class, provide explicit hook-in points via <a href="https://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">the strategy pattern</a>, it\'s a more readable way to accomplish this, plus, it\'s easier to keep this sort of API stable as you\'re in full control over what behaviors they can and can not change.</li>\n<li>If you\'re trying to follow the open-closed principle by using inheritance to avoid adding a much-needed update to a class, just don\'t. Update the class. Your codebase will be much cleaner if you actually take ownership of the code you\'re hired to maintain instead of trying to tack stuff onto the side of it. If you\'re scared about introducing bugs, then get the existing code under test.</li>\n<li>If you need to reuse code, start out by trying to use composition or helper functions.</li>\n</ul>\n<p>Finally, if you\'ve decided that there\'s no other good option, and you must use inheritance to achieve the code-reuse that you need, then you can use it, but, follow these four <strong>P.A.I.L.</strong> rules of restricted inheritance to keep it sane.</p>\n<ol>\n<li>Use inheritance as a <strong>private</strong> implementation detail. Don\'t expose your base class publicly, use interfaces for that. This lets you freely add or remove inheritance as you see fit without making a breaking change.</li>\n<li>Keep your base class <strong>abstract</strong>. It makes it easier to divide out the logic that needs to be shared from the logic that doesn\'t.</li>\n<li><strong>Isolate</strong> your base and child classes. Don\'t let your subclass override base class methods (use the strategy pattern for that), and avoid having them expect properties/methods to exist on each other, use other forms of code-sharing to achieve that. Use appropriate language features to force all methods on the base class to be non-overridable (&quot;final&quot; in Java, or non-virtual in C#).</li>\n<li>Inheritance is a <strong>last</strong> resort.</li>\n</ol>\n<p>The <strong>Isolate</strong> rule in particular may sound a little rough to follow, but if you discipline yourself, you\'ll get some pretty nice benefits. In particular, it gives you the freedom to avoid all of the main nasty pitfalls associated with the inheritance that were mentioned above.</p>\n<ul>\n<li>It\'s much easier to follow the code because it doesn\'t weave in and out of base/sub classes.</li>\n<li>You can not accidentally leak when your methods are internally calling other overridable methods if you never make any of your methods overridable. In other words, you won\'t accidentally break encapsulation.</li>\n<li>The fragile base class problem stems from the ability to depend on accidentally leaked implementation details. Since the base class is now isolated, it will be no more fragile than a class depending on another via composition.</li>\n<li>The deadly diamond of death isn\'t an issue anymore, since there\'s simply no need to have multiple layers of inheritance. If you have the abstract base classes B and C, which both share a lot of functionality, just move that functionality out of B and C and into a new abstract base class, class D. Anyone who inherited from B should update to inherit from both B and D, and anyone who inherited from C should inherit from C and D. Since your base classes are all private implementation details, it shouldn\'t be too difficult to figure out who\'s inheriting from what, to make these changes.</li>\n</ul>\n<h2>Conclusion</h2>\n<p>My primary suggestion would be to use your brain on this matter. What\'s far more important than a list of dos and don\'ts about when to use inheritance is an intuitive understanding of inheritance and its associated pros and cons, along with a good understanding of the other tools out there that can be used instead of inheritance (composition isn\'t the only alternative. For example, the strategy pattern is an amazing tool that\'s forgotten far too often). Perhaps when you have a good, solid understanding of all of these tools, you\'ll choose to use inheritance more often than I would recommend, and that\'s completely fine. At least, you\'re making an informed decision, and aren\'t just using inheritance because that\'s the only way you know how to do it.</p>\n<p>Further reading:</p>\n<ul>\n<li><a href="https://javascript.plainenglish.io/composition-alone-cant-replace-inheritance-606760f03d60?source=friends_link&amp;sk=24f58b20b2d4162404376c6f7ec16301" rel="nofollow noreferrer">An article</a> I wrote on this subject, that dives even deeper and provides examples.</li>\n<li><a href="https://yourbasic.org/golang/inheritance-object-oriented/" rel="nofollow noreferrer">A webpage</a> talking about three different jobs that inheritance does, and how those jobs can be done via other means in the Go language.</li>\n<li><a href="https://programming.guide/java/when-to-create-a-final-class.html" rel="nofollow noreferrer">A list</a> of reasons why it can be good to declare your class as non-inheritable (e.g. &quot;final&quot; in Java).</li>\n<li>The &quot;Effective Java&quot; book by Joshua Bloch, item 18, which discusses composition over inheritance, and some of the dangers of inheritance.</li>\n</ul>\n'}, {'answer_id': 72260196, 'author': 'Mohamed Reda', 'author_id': 6462376, 'author_profile': 'https://Stackoverflow.com/users/6462376', 'pm_score': 0, 'selected': False, 'text': '<p>Simply, implementation is like rules you (the class) should follow</p>\n<p>But extend is like using common code for a lot of classes, and maybe just one of them that you need to override.</p>\n'}, {'answer_id': 74021528, 'author': 'Alexey Nikitenko', 'author_id': 4316802, 'author_profile': 'https://Stackoverflow.com/users/4316802', 'pm_score': 0, 'selected': False, 'text': '<p>Just opinion, inheritance should only be used when:</p>\n<ul>\n<li>Both classes are in the same logical domain</li>\n<li>The subclass is a proper subtype of the superclass</li>\n<li>The superclass’s implementation is necessary or appropriate for the subclass</li>\n<li>The enhancements made by the subclass are primarily additive.</li>\n</ul>\n<p>There are times when all of these things converge:</p>\n<ul>\n<li>Higher-level domain modeling</li>\n<li>Frameworks and framework extensions</li>\n<li>Differential programming</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/49002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4883/']