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:
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
Can I do something about that ? Are there something I don't know about Java ? Or is my design bad ? Or.. ?
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.
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
Yes, an abstract class can have a constructor in Java. The compiler automatically adds the default constructor in every class either it is an abstract class or concrete class.
Abstract classes do not support multiple inheritance.
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:
interface AbstractClassFactory {
AbstractClass create( Type arg0, Type arg1, Type arg2 );
AbstractClass create( Type onlyOneArg );
}
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