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).
No, constructors cannot be inherited in Java. In inheritance sub class inherits the members of a super class except constructors. In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors.
When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With