Note that there are some explanatory texts on larger screens.

plurals
  1. POOverride beats Overload? Why does that make sense at all?
    text
    copied!<p><strong>Why should a super method hand out it's <em>this</em> reference as super type instead of own type?</strong> </p> <p>I don't understand the practicality of this behavior. I learned to code against Types/Interfaces and not against classes, but considering this kind of behavior I'm confused about everything I thought OOP was standing for. This breaks possibility of clean code and forces me to fill it with verbose control flow like heavy use of the <em>instanceof</em> operator. <em>Why does that kind of behavior make even sense?</em> </p> <p><strong>Abstract:</strong><br> Consider this code:</p> <pre><code>abstract class A { public void visit(Target t) { t.method(this); } } </code></pre> <p>If <code>Target</code> overloads <code>method()</code> with A and different child classes of A in it's signature and these children don't override <code>visit(Target t)</code> themselves then overloaded <code>method(A a)</code> will be choosen by compiler always.</p> <p><strong>Working example:</strong> <a href="http://pastebin.com/EGNpY7pF" rel="nofollow">http://pastebin.com/EGNpY7pF</a></p> <p><strong>Code Snip</strong></p> <pre><code>public class Target { public static abstract class A { void visit(Target t) { t.method(this); } } public static class B extends A {} public static class C extends A { @Override void visit(Target t) { t.method(this); } } void method(A a) { System.out.println("A");} void method(B b) { System.out.println("B");} void method(C c) { System.out.println("C");} public static void main(String[] args) { Target t = new Target(); A ab = new B(); B b = new B(); A ac = new C(); C c = new C(); ab.visit(t); b.visit(t); ac.visit(t); c.visit(t); } </code></pre> <p>}</p> <p><strong>Output</strong> A A C C<br> Which is really akward since <code>ac</code> is referenced to as <code>A</code>-Type but still <code>C</code>'s overriden <code>visit()</code> method is called.</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