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);
}
[...]
}
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
If you want to access private variables, best practice is to write getter and setter methods in super class and use them wherever you want. Show activity on this post. You have marked the variables in super class as private which means they won't be inherited. mark them as public,default,or protected and test.
Subclass Constructors Invocation of a superclass constructor must be the first line in the subclass constructor.
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.
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.
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