In the following example if I make a constructor of a class called example like so:
public class Example{
public Example(){
this.super();
}
}
The above will not work because javac Example.java
informs about following compilation error:
Example.java:3: error: illegal qualifier; Object is not an inner class
this.super();
^
1 error
But shouldn't it work as instead of implicitly stating this
by using super()
, we are explicitly stating it by using this
?
Although invoking a superclass constructor by calling super(args)
looks like it’s a regular method call, that syntax is actually different from a typical method call and isn’t subject to the same rules. For example:
- You can only use
super(args)
in a constructor. - You can only use
super(args)
as the first line of a constructor.
In that sense, it probably helps to think of this not as a method call, but simply as a way of telling Java what you want to do to initialize the superclass.
Because this isn’t a typical method call, the rules for regular method calls don’t apply to it. As a result, you can’t prefix it with this.
to make the receiver object explicit. There’s no fundamental reason why the Java language designers couldn’t have made this syntax legal; they just chose not to do so.