I have an abstract class which has a constructor that takes varargs. The Java compiler doesn't seem to require that child classes call super() even though every constructor takes arguments.
public abstract class Parent {
public Parent(String... varargs) {
}
}
public class Child extends Parent {
// I would like this to be a compile error. Child should always call super().
}
How can I write Parent
so that children must call super()
?
You need a call to super() if and only if there's no default constructor (accepting no arguments) for your parent class . In all other cases (where a constructor with zero arguments exists) you don#t have to code it. It's implicitly called anyway.
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.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
In Java, the superclass constructor can be called from the first line of a subclass constructor by using the special keyword super() and passing appropriate parameters, for example super(); or super(theName); as in the code below.
The purpose of a varargs method is to allow the programmer to write each argument individually, so it's possible to prepend a required argument of the same type to make sure at least one is passed in. For callers that have a list or array, an alternate constructor can accept Iterable
.
public abstract class Parent2 {
public Parent2(String firstArg, String... varargs) {
}
public Parent2(Iterable<? extends String> args) {
}
}
public class Child2 extends Parent2 {
public Child2() {
super("abc");
}
}
From the docs, the number of parameters passed to a method/constructor accepting a varargs
parameter, can be none, making the constructor act as a default parameter less constructor too.
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
So you could change it to an array,
abstract class Parent {
public Parent(String[] varargs) {
}
}
your child constructor would be forced to call this constructor explicitly.
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