Let’s consider this piece of code as our example:
import java.awt.*;
class Maze extends Panel{
String name;
public static void main(String[] args){
Maze m = new Maze();
System.out.println(m.setName("Hello World").getName());
}
public Maze setName(String name){
this.name = name;
return this;
}
public String getName(){
return name;
}
public void paint(){
}
}
I’m trying to understand method chaining, and as what answers said on other questions, use return this. I tried it and yes it works, but not on mutator methods like the method setName() above. Why is the compiler outputting:
The return type is incompatible with Component.setName(String)
Unless Maze derives from some other class that defined
setName(String), theMaze setName(String name)signature should be perfectly acceptableNote: You should write
this.name = name;UPDATE: as it turns out, Maze is deriving from a
Panel(which is deriving fromComponent). AsComponent.setName(String)specifies its return type asvoid(void setName(String)), you cannot specify any other return type, butvoidforsetName()in your class. The reason is inheritance: if someone has a reference to yourMazeobject via aComponentreference (e.g.Component c = new Maze();), and callssetName(), the runtime knows to call yours, because of the inheritance. However your version is returning a value, with which the runtime has to do something, but the code is not prepared for it (it was compiled with the knowledge of aComponent.