Note that there are some explanatory texts on larger screens.

plurals
  1. POJava overloading method selection
    primarykey
    data
    text
    <p>I'm trying to get my head round how Java selects which method is executed:</p> <pre><code>//Example 1 prints Square:add(Figure) Figure fs = new Square(); fs.add(fs); //Example 2 prints Square:add(Figure) Rectangle rs = new Square(); rs.add(fs); //Example 3 prints Rectangle:add(Rectangle). Expected Square:add(Square) rs.add(new Square()); //Example 4 prints Rectangle:add(Rectangle). Expected Square:add(Figure) Square ss = new Square(); ss.add(rs); class Figure { public void add(Figure f){ System.out.println("Figure:add(Figure)"); } } class Rectangle extends Figure { @Override public void add(Figure f){ System.out.println("Rectangle:add(Figure)"); } public void add(Rectangle r){ System.out.println("Rectangle:add(Rectangle)"); } } class Square extends Rectangle { @Override public void add(Figure f){ System.out.println("Square:add(Figure)"); } public void add(Square s){ System.out.println("Square:add(Square)"); } } </code></pre> <p>What I've learned <a href="https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type">here</a> is</p> <ul> <li>Method signature gets determined based on compile time data types</li> <li>Actual method invoked depends on the dynamic type of the object the method is called on.</li> </ul> <p>Based on that, the result of the first two calls is as expected. However, I don't understand the result of example 3 and 4.</p> <p>It seems to be specified in the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12" rel="nofollow noreferrer">java language specification</a>, but I don't understand it.</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.
 

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