I have a class derived from RuntimeException and a function as below.
public class MyException extends RuntimeException {
// No contructor implemented;
// This class inherits the constructors from its parent;
}
public static void main(String[] args) {
String msg = "msg";
MyException baseException = new MyException(); // No compiling error
MyException baseException2 = new MyException(msg); // Compiling error: Expected 0 arguments but found 1
}
It looks like MyException inherits the default constructor from RuntimeException,
but it does not inherit the 1-arg constructor RuntimeException(String message).
Is this expected? Why is Java designed like this?
I noticed that the similar question was discussed at Java Constructor Inheritance. That link does not answer my question since: They said Java does not support constructor inheritance, but based on my above observation, Java does support the inheritance of the default constructor, but it does not support the 1-arg constructor. Thus I am not sure of the correctness of the answers in that link.
@Slaw gave an excellent answer: the default constructor is not from inheritance -- it is added by the compiler; Also how the default constructor and other constructors are invoked; In what situation, the compile will fail. I have upvoted that answer.
MyExceptiondoes not have a 1-argument constructor. No other explanation required.RuntimeExceptionis not inherited. You haven't givenMyExceptiona constructor, and so a default one is implicitly added by the compiler. That default constructor invokes the superclass's no-argument constructor (as all constructors implicitly try to do when there's no explicit call tosuper(...)orthis(...)). If such a constructor does not exist or is not visible, then the subclass fails to compile.