Java overloading method selection

前端 未结 2 2033
遥遥无期
遥遥无期 2020-12-17 14:13

I\'m trying to get my head round how Java selects which method is executed:

//Example 1 prints Square:add(Figure)
Figure fs = new Square();
fs.add(fs);

//Ex         


        
2条回答
  •  一整个雨季
    2020-12-17 15:00

    rs.add(new Square());
    

    The declared type of rs is Rectangle. So it looks at a method in Rectangle and all superclasses taking a Square or a type compatible with Square as argument. The most specific one is add(Rectangle) since Square is a Rectangle, and since Rectangle is more specific than Figure.

    Square ss = new Square();
    ss.add(rs);
    

    Looks for a method add(Rectangle) in Square and all super-classes. Rectangle.add(Rectangle) is chosen, since Square.add(Square) doesn't apply (a Rectangle is not a Square), and Square.add(Figure) is less specific.

提交回复
热议问题