Java: Calling super()
super()
calls the constructor of the base class.
☞
Not to be confused with super.someMethod()
. See Calling super.someMethod().
Another Example
Here's an expanded version with printouts and constructor arguments.
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints the following:
Constructing an animal: From Dog constructor Constructing a dog.
The Fine Print
- The call to
super()
must be the first statement in the constructor. - If you give arguments to
super("hello", 5)
, it will invoke the base constructor that accepts aString
and anint
. super()
without arguments calls the base class' no-arg constructor. Such constructor only exists if A) you have not defined any constructor, or B) you have explicitly defined a no-arg constructor. If neither of these are true, thensuper()
will fail with a compile error.
Comments
Be the first to comment!