The keyword super refers to the superclass and can be used to invoke the superclass’s methods and constructors.
A subclass inherits accessible data fields and methods from its superclass. Does it inherit
constructors? Can the superclass’s constructors be invoked from a subclass? This section
addresses these questions and their ramifications.
Two ways of using
The keyword super refers to the superclass of the class in which super appears. It can be used in two ways:
To call a superclass constructor.
To call a superclass method.
Calling Superclass Constructors
A constructor is used to construct an instance of a class. Unlike properties and methods, the constructors of a superclass are not inherited by a subclass. They can only be invoked from the constructors of the subclasses using the keyword super.
The syntax to call a superclass’s constructor is:
super(), or super(parameters);
The statement super() invokes the no-arg constructor of its superclass, and the statement super(arguments) invokes the superclass constructor that matches the arguments. The statement super() or super(arguments) must be the first statement of the subclass’s constructor; this is the only way to explicitly invoke a superclass constructor.
A constructor may invoke an overloaded constructor or its superclass constructor. If neither is invoked explicitly, the compiler automatically puts super() as the first statement in the constructor. For example:
In any case, constructing an instance of a class invokes the constructors of all the superclasses along the inheritance chain. When constructing an object of a subclass, the subclass constructor first invokes its superclass constructor before performing its own tasks. If the superclass is derived from another class, the superclass constructor invokes its parent-class constructor before performing its own tasks. This process continues until the last constructor along the inheritance hierarchy is called. This is called constructor chaining.
Calling Superclass Methods
The keyword super can also be used to reference a method other than the constructor in the superclass. The syntax is:
How does a subclass invoke its superclass’s constructor?
True or false? When invoking a constructor from a subclass, its superclass’s no-arg constructor is always invoked.