Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Inherit constructor

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).

like image 887
Mike Avatar asked Sep 06 '09 00:09

Mike


People also ask

Does Java inherit constructor?

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.

What is constructor in inheritance?

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.


1 Answers

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.

like image 199
ChssPly76 Avatar answered Oct 11 '22 09:10

ChssPly76