If we use super()
to access Throwable
class’ printStackTrace()
method as that is what is used by DefaultExceptionHandler
, then that could be done with this
also as because of inheritance, printStackTrace
is available in our own custom defined exception class as well.
Please let me know if I got something wrong?
class AlsCustomException extends Exception
{
public AlsCustomException(String message)
{
super(message);
}
}
Consider this code snippet above. super
is a reference variable that points to the object of super class created automatically when an instance of the child class in created then, what is super()..
?
class AlsCustomException extends Exception
{
public AlsCustomException(String message)
{
this(message);
}
}
I am expecting that above code snippet should work just as fine as well.
Bawa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
The 2nd code sample tries to recursively call the same AlsCustomException
constructor over and over. It doesn’t compile, but if it did, it would die with a StackOverflowException
. In the 1st code block, super(...)
calls the the parent class constructor, i.e., the Exception
constructor.
You can call a method with the super
keyword as well, to explicitly call the base class’ method. This only makes sense when the current class overwrites it, so unless you overwrite printStackTrace
, super.printStackTrace()
and this.printStackTrace()
and plain old printStackTrace()
call the same method.
See the Java tutorial.