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
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.