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).
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.
The other replies are correct that Java won't let you inherit constructors. But IDEs can be used to help ease the massive burden of creating these for all your classes.
In Eclipse go to the "Source" menu and select "Generate Contructors from Superclass...". You can also select this as an option when using the dialog to create a new class.
Inheritance
SUMMARY: A subclass inherits all the
members (fields, methods, and nested
classes) from its superclass.
Constructors are not members, so they
are not inherited by subclasses, but
the constructor of the superclass can
be invoked from the subclass.
You can't in java. You can't give a method arguments without explicitly declaring them in the method. Doing this probably wouldn't be the best idea, it could lead to very confusing code and over-complicate things. The alternative of having to type a few extra characters isn't that bad. :D
If you have a default value you want to assign you could create an empty constructor in the base class that calls the parameterized constructor.
This would remove the need to child classes to call the parameterized constructors.