Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sorry for necroposting, but it seems that the question and the answers concentrate on code reuse. We can use both inheritance and composition to reuse some code from the common "ancestor", it's true. And composition works better here.</p> <p>But inheritance is primarily not for code reuse, it's for <strong>dynamic binding</strong>. The "is a" relationship can be practically formulated as follows: calling code is using interface of the object and knows nothing about particular implementation.</p> <p>Pseudocode:</p> <pre><code>// Interface class A { drawMe() {} ; }; // Implementations class Rect:A { drawMe() {DrawRect();}; }; class Circle:A { drawMe() {Drawcircle();}; }; main() { // We fill the array in one part of the program Array_of_A arr; arr.add(new Rect); arr.add(new Circle); // We can use the array in completely another part // without any idea of what the items really are, // only know the interface foreach(item from arr) { item-&gt;drawMe(); } } </code></pre> <p>In many languages (e.g. like C++) inheritance is the only practical way to say "this object implements this interface". And also it allows to do some things like code reuse, which really are better done with composition.</p> <p>I know nothing of Go, but I understand your words correctly, it offers another way of defining "this object implements this interface": </p> <blockquote> <p>every object, that has methods defined by an interface, implements this interface implicite</p> </blockquote> <p>So if you also can call the objects by interface, it does the work of inheritance. But it additionally allows the substitution of the base class, which is why I think they call it composition. And maybe because of it being internally implemented in some way other than vtable, but I can't think of where it can make any difference.</p> <p>So, <strong>inheritance can be replaced by composition</strong> if you find a way to say "this object implements this interface".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload