Note that there are some explanatory texts on larger screens.

plurals
  1. POjava override method invocation
    primarykey
    data
    text
    <p>I have a super class:</p> <pre><code>public class SuperClass { public void dosomething() { firstMethod(); secondMethod(); } public void firstMethod() { System.out.println("Super first method"); } public void secondMethod() { System.out.println("Super second method"); } } </code></pre> <p>A sub class:</p> <pre><code>public class SubClass extends SuperClass { public void dosomething() { super.dosomething(); } public void firstMethod() { System.out.println("Sub first method"); } public void secondMethod() { System.out.println("Sub second method"); } } </code></pre> <p>A test class:</p> <pre><code>public static void main(String[] args) { SubClass sub = new SubClass(); sub.dosomething(); SuperClass sup = new SuperClass(); sup.dosomething() } </code></pre> <p>when I run the test method, I got this:</p> <pre><code>Sub first method Sub second method </code></pre> <p>Can you tell me how this happened? In the sub class <code>dosomething</code> method, I called <code>super.dosomething()</code> and I think the super method will be called, but the override method in sub class was called.</p> <p>if I do this:<br/> <code>SuperClass superClass = new SuperClass();<br/> superClass.dosomething();</code><br/> <br/> the result is:<br/> Super first method<br/> Super second method<br/></p> <p>The difference is method invocation place. I think there must be something I don`t know ):</p> <p>oops!the super reference pointed to subclass in the first example...</p> <p>like this:<br/></p> <p><code> SuperClass sub = new SubClass();<br/> sub.firstMethod();<br/> sub.secondMethod();<br/> </code></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.
 

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