Reputation: 18586
I was wondering if i have an abstract super class with x different constructors, and i want to be able to use all those constructors in a subclass, do i have to write all x constructors in the subclass and just let them all call super(...) ? Seems like redundant code..
An example for the clarity:
public class SuperClass {
public SuperClass() {
...
}
public SuperClass(double d) {
...
}
public SuperClass(BigDecimal b) {
...
}
public SuperClass(BigDecimal b, String s) {
...
}
[...]
}
Do i than need:
public class SuperClass {
public SubClass() {
super();
}
public SubClass(double d) {
super(d);
}
public SubClass(BigDecimal b) {
super(b);
}
public SuperClass(BigDecimal b, String s) {
super(b, s);
}
[...]
}
Upvotes: 5
Views: 618
Reputation: 18747
If you want every type of constructor in both parenr and child, then yes, you need to specify them explicitly, but no need to call super()
explicitly.
Upvotes: 1
Reputation: 26418
you can have a code like this:
public class SuperClass {
public SuperClass() {
...
}
public SuperClass(double d) {
...
}
public SuperClass(BigDecimal b) {
}
public SuperClass(BigDecimal b, String s) {
this(b);
}
[...]
}
And have a subclass as:
public class SubClass extends SuperClass{
public SubClass() {
super();
}
public SubClass(double d) {
super(d);
}
public SuperClass(BigDecimal b, String s) {
super(b, s);
}
[...]
}
Upvotes: 1
Reputation: 22332
You do not need to supply constructors for every overload of base's constructors. You simply need one. If your base constructor offers a default (parameterless) constructor, then you do not even need to provide a constructor yourself. The compiler will automatically generate a default constructor for your class that automatically calls the default constructor of your base class.
Note: it is not necessary to call super()
directly, as it is implied without parameters. It is only required when no default constructor exists.
Seeing that many different constructors, and the fact that you do not need them all might imply that the parent class is doing too much.
Upvotes: 2
Reputation: 7943
But you have to do it this way. As this way you are deciding what you want to expose in the subclass. Also some constructors might be not appropriate for a sub class thus this is not working by default without you coding it explicitly.
Upvotes: 5