Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you only want to call methods from the interface (good!), then you usually don't need to now the name of the implementor.</p> <pre><code>getRunnableFromSomewhere().run(); </code></pre> <p>always works and calls the <code>run()</code> method on the instance that is returned by that method.</p> <p>If you want to now the class name at runtime, simpy call <code>getClass().getName()</code> on the instance:</p> <pre><code>System.out.println(getRunnableFromSomewhere().getClass().getName()); </code></pre> <hr> <p>A simple example with the <code>Number</code> interface:</p> <pre><code>public class NumberExample { public static void main(String[] args) { MagicNumber magic = MagicNumberProvider.get(); // a random implementation System.out.println(magic.getMagicNumber().doubleValue()); // We know nothing about the implementations } } class MagicNumberProvider { public static MagicNumber get() { return Math.random() &gt; 0.5d ? new ItsMagicOne() : new ItsMagicTwo(); } } interface MagicNumber { public Number getMagicNumber(); } class ItsMagicOne implements MagicNumber { @Override public Number getMagicNumber() {return new Long(1);} } class ItsMagicTwo implements MagicNumber { @Override public Number getMagicNumber() {return new Double(2.5);} } </code></pre> <p>It only calls interface methods and we have, from the perspective of the main method, no idea, which implementation of <code>MagicNumber</code> is used (it's random) and on which implementation of <code>Number</code> we actually call the <code>doubleValue()</code> method.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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