Basically, I have:
public abstract class AbstractClass {
public AbstractClass( Type arg0, Type arg1, Type arg2 ) {
// do some stuff with all those args
}
public AbstractClass( Type onlyOneArg ) {
// do different stuffs with this different arg.
}
protected someMethods() { /* ... */ }
}
And I have a few problems in the subclasses:
- First, I have to -in most of the cases- uselessly rewrite the constructors. Not very annoying, just a bit dirty to the eye.
- And, more important, I am not forced to implement both constructors (although both are used in the program).
Example of my current subclasses:
public class MyClass extends AbstractClass {
public MyClass( Type arg0, Type arg1, Type arg2 ) {
super( arg0, arg1, arg2 );
}
public MyClass( Type onlyOneArg ) {
super( onlyOneArg );
}
}
And
- I have to be able to write some particular code in a subclass’s constructor if I want.
- I have too many shared code that I want to keep in the abstract class.
Can I do something about that ?
Are there something I don’t know about Java ? Or is my design bad ? Or.. ?
The subclass has to call either one (or both, if you redefine both as in your example) of the superclass constructors; but you cannot force it to redefine constructors with the same signatures of the superclass.
The only way to guarantee that a superclass constructor is called is to have only one constructor in the superclass.
I think you should think of a way to redesign your superclass (maybe creating 2 classes) to have only one constructor if you want it to always be called.
But, if want a specific constructor to be present in a subclass, you should isolate the “construction” concern in a factory; where you can have special factory classes for each of your subclasses. Your factories would implement this interface: