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.

6
  • 1
    Your question is answered by David Santamaria's answer in the question you linked. Commented Jul 28, 2023 at 5:49
  • 1
    Nothing in Java 'supports constructor inheritance'. Constructors are not inherited. MyException does not have a 1-argument constructor. No other explanation required. Commented Jul 28, 2023 at 5: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. Commented Jul 28, 2023 at 5:57
  • 1
    Regarding "Why is Java designed like this?": see Why are constructors not inherited in Java? Commented Jul 28, 2023 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.) Commented Jul 28, 2023 at 16:43

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.