Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make a class, which I can't change, implement an interface?
    text
    copied!<p>I have a class from another library that is closed-source, but I want to be able to use an interface for it. The reason being that I don't want to do <code>instanceof</code> checks or <code>null</code>-checks everywhere, but I also don't want to extend the existing class.</p> <p>For example, let's say I have this code:</p> <pre><code>public class Example { // QuietFoo is from another library that I can't change private static QuietFoo quietFoo; // LoudFoo is my own code and is meant to replace QuietFoo private static LoudFoo loudFoo; public static void main(String[] args) { handle(foo); } private static void handle(Object foo) { if (foo instanceof QuietFoo) ((QuietFoo) foo).bar(); else if (foo instanceof LoudFoo) ((LoudFoo) foo).bar(); } } </code></pre> <p>I can't change <code>QuietFoo</code>:</p> <pre><code>public class QuietFoo { public void bar() { System.out.println("bar"); } } </code></pre> <p>But I <em>can</em> change <code>LoudFoo</code>:</p> <pre><code>public class LoudFoo { public void bar() { System.out.println("BAR!!"); } } </code></pre> <p>The problem is, there may be many other implementations of <code>bar</code> in many classes, and there may be more methods than just <code>bar</code>, so not only would my <code>handle</code> method get slow and ugly with lots of <code>instanceof</code> statements, but I would have to write one of these handle methods for each method on <code>QuietFoo</code> and <code>LoudFoo</code>. Extending isn't a viable solution because it violates the whole <em>is-a</em> contract since <code>LoudFoo</code> is not a <code>QuietFoo</code>.</p> <p>Basically, given <code>Foo</code>:</p> <pre><code>public interface Foo { void bar(); } </code></pre> <p>How can I make <code>QuietFoo</code> implement <code>Foo</code> without changing its source so I don't have to do casting and <code>instanceof</code> calls everywhere in my code?</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