Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The second method is called <em>delegation</em>. There is also <em>composition</em> - when <code>A</code> is a member of <code>B</code>.</p> <p>The difference between the two is that if <code>A</code> is not in the same package as <code>B</code> (package access is a different case - left as exercise for the reader) - then in case of <em>delegation</em> or <em>composition</em> you will have access only to public data members and methods of class <code>A</code>, whereas in case of <em>inheritance</em>, the inheriting class <code>B</code> will have access to public <strong>and protected</strong> members and methods of class <code>A</code>.</p> <p><strong>Update</strong></p> <p>There are a lot of additional differences even in the case that all methods and members of <code>A</code> are accessible to <code>B</code> (most of them relate to the case when you are not the owner of both classes, rather when <code>A</code> is provided to you by a third party and you don't have control over its access modifiers).</p> <p>But even if you do have the control and can define all of the members and methods of <code>A</code> as <strong>public</strong> - do you want to? It would introduce a horde of additional maintenance issues - most important, IMO, is that <strong>anything</strong> you define as <strong>public</strong> is a contract between you and the user of your code - perhaps someone in a different part of the planet. Which in turn means that you can't hide your implementation details, your private utility methods or anything from him - nothing prevents him from using some method, that you wrote only for some inner calculation, directly.</p> <p>What that means is - when tomorrow you decide that you don't want to maintain that method again or that it introduces some sort of performance or security issue - you can't remove it. <em>Someone already uses it.</em></p> <p><strong>Another update</strong></p> <p>As mentioned below, and something that I haven't mentioned, in the case of <em>inheritance</em> you also receive a "free gift" - <strong>polymorphism</strong>. <strong><a href="http://download.oracle.com/javase/tutorial/java/IandI/polymorphism.html" rel="nofollow">See here.</a></strong></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