Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>An <code>interface</code> in Java is nothing more but a contract; at the compiler level, the only contract is that if you <code>implements</code> an interface, you must have an implementation of all methods (for classes which are not <code>abstract</code>):</p> <pre><code>public interface Foo { /* * Any invocation of this method sends the instance to the moon */ void foo(); } </code></pre> <p>If you have a concrete class which you can instantiate and which implements <code>Foo</code>, such as:</p> <pre><code>public class MyClass implements Foo { // must implement foo() @Override public void foo() { stayOnEarth(); } } </code></pre> <p>then you can do:</p> <pre><code>final Foo foo = new MyClass(); </code></pre> <p>As you have a reference to an instance of type <code>Foo</code>, it means you can invoke <code>foo()</code> on it:</p> <pre><code>foo.foo(); </code></pre> <p>The JVM will look up method <code>foo()</code> and find it.</p> <p>Now: <strong>the fact that you have implemented <code>foo()</code> is one thing; the fact that you obey the contract of this interface is another. The compiler does not give a &lt;beep&gt; if you stay on Earth or go right to Antares: it cannot enforce that</strong>.</p> <p>This is a question of trust first and foremost: if you implement an interface, you are expected to understand what this interface means; which is why there is documentation. The compiler cannot help any further but to enforce that you <em>at least</em> implement the needed methods.</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