0

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.

leo
  • 357
  • 2
  • 15
  • 1
    Your question is answered by David Santamaria's answer in the question you linked. – Sweeper Jul 28 '23 at 05:49
  • 1
    *Nothing* in Java 'supports constructor inheritance'. Constructors are not inherited. `MyException` does not *have* a 1-argument constructor. No other explanation required. – user207421 Jul 28 '23 at 05:49
  • 4
    The no-argument constructor of `RuntimeException` is not inherited. You haven't given `MyException` a 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 to `super(...)` or `this(...)`). If such a constructor does not exist or is not visible, then the subclass fails to compile. – Slaw Jul 28 '23 at 05:57
  • 1
    Regarding "Why is Java designed like this?": see [Why are constructors not inherited in Java?](https://stackoverflow.com/questions/18147768/why-are-constructors-not-inherited-in-java) – Rogue Jul 28 '23 at 16:01
  • If I explicitly define a constructor, say a 1-arg constructor, will the compiler still add the default one? (It seems not from what I observed.) – leo Jul 28 '23 at 16:43
  • The default constructor is only added by the compiler if no other constructor is explicitly defined. And if you give `MyException` a one-argument constructor, say for the message argument, and you want it to behave like the equivalent constructor of `RuntimeException`, its implementation would look like: `public MyException(String msg) { super(msg); }`. – Slaw Jul 28 '23 at 18:05

0 Answers0