views:

271

answers:

5

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 {
 A(int x) {
  ///
 }
}

class B extends A {

}

class C extends A {

}

#Implicit super constructor A() is undefined for default constructor.

I dont want to have to write B(int x) and 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 this particular design, I want to require the user to specify certain parameters in the constructor.

+7  A: 

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.

ChssPly76
+2  A: 

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

CrazyJugglerDrummer
A: 

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.

adatapost
+3  A: 

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.

Matt
Hmmm ... one person's "massive burden" is another person's trivial task.
Stephen C
A: 

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.

Fortyrunner