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.