Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you delegate, you are simply calling up some class which knows what must be done. You do not really care <em>how</em> it does it, all you <em>care</em> about is that the class you are calling knows what needs doing. </p> <p>If I were you though I would make an interface and name it <code>IPrinter</code> (or something along those lines) which has one method named <code>print</code>. I would then make <code>RealPrinter</code> implement this interface. Finally, I would change this line: <code>RealPrinter p = new RealPrinter();</code> to this: <code>IPrinter p = new RealPrinter()</code>.</p> <p>Since <code>RealPrinter</code> implements <code>IPrinter</code>, then I know for sure that it has a <code>print</code> method. I can then use this method to change the printing behaviour of my application by delegating it to the appropriate class. </p> <p>This usually allows for more flexibility since you do not embed the behaviour in your specific class, but rather leave it to another class. </p> <p>In this case, to change the behaviour of your application with regards to printing, you just need to create another class which implements <code>IPrinter</code> and then change this line: <code>IPrinter p = new RealPrinter();</code> to <code>IPrinter p = new MyOtherPrinter();</code>.</p> <pre><code>public interface IPrinter { void print(); } public class RealPrinter implements IPrinter { @Override public void print() { System.out.println("This is RealPrinter"); } } public class RealPrinter2 implements IPrinter { @Override public void print() { System.out.println("This is RealPrinter2"); } } public class Main { public static void main(String...arg){ IPrinter printer = new RealPrinter(); printer.print(); printer = new RealPrinter2(); printer.print(); } } </code></pre>
 

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