Java: Inherit constructor

inheritance, java, oop

Solution

You can't. If you want to have a parameterized constructor in your base class - and no no-argument constructor - you will have to define a constructor (and call `super()` constructor) in each of descendant classes.

Problem

I want to have a constructor with an argument that gets inherited by all child classes automatically, but Java won't let me do this ``` class A { public A(int x) { // Shared code here } } class B extends A { // Implicit (int x) constructor from A } class C extends A { // Implicit (int x) constructor from A } ``` I don't want to have to write `B(int x)`, `C(int x)`, etc. for each child class. Is there a smarter way of approaching this problem? Solution #1. Make an `init()` method that can be called after the constructor. This works, although for my particular design, I want to require the user to specify certain parameters in the constructor that are validated at compile time (e.g. Not through varargs/reflection).

Original source