Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.</p> </blockquote> <p>We can't. Interfaces aren't used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword <code>implements</code> rather than <code>extends</code>.</p> <blockquote> <p>Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?</p> </blockquote> <p>They are not. With interfaces a single class can have several "<em>views</em>", different APIs or capabilities. E.g. A class can be <code>Runnable</code> and <code>Callable</code> at the same time, while both methods are effectively doing the same thing.</p> <blockquote> <p>Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.</p> </blockquote> <p>Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the <a href="http://en.wikipedia.org/wiki/Diamond_problem"><em>Diamond problem</em></a>).</p> <p>There are few use-cases for interfaces:</p> <ol> <li><p>Object effectively has two identities: a <code>Tank</code> <em>is</em> both a <code>Vehicle</code> and a <code>Weapon</code>. You can use an instance of <code>Tank</code> where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).</p></li> <li><p>Simple responsibilities: an instance of <code>Tank</code> object in a game is also <code>Runnable</code> to let you execute it in a thread and an <code>ActionListener</code> to respond to mouse events.</p></li> <li><p>Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.</p></li> <li><p>Marker interfaces: not adding any methods, but easily accessible via <code>instanceof</code> to discover object capabilities or wishes. <code>Serializable</code> and <code>Cloneable</code> are examples of this.</p></li> </ol> <p>What you are looking for are trait (like in Scala), unfortunately unavailable in Java.</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