In general Describe when, where, and how is super keyword used in a constructor.
Ans:-
Super keyword:-
* The super
keyword refers to
superclass (parent) objects. It is used inside a sub-class method
definition to call a method defined in the super class. Private
methods of the super-class cannot be called. Only public and
protected methods can be called by the super
keyword.
It is also used by class constructors to invoke constructors of its
parent class.
* The most common use of the super
keyword is to eliminate the confusion between superclasses and
subclasses that have methods with the same name. super() should be
first statement inside any constructor. It can be used only inside
constructor and nowhere else. super() is used to refer only parent
class’s(super class’s) constructor.
* Super keyword (super() ) is used to call Base class’s constructor(i.e, Parent’s class).
How a super keyword used in a constructor can be understand by a simple program:-
class
Parent {
Parent()
{
System.out.println(
"Parent
class's No "
+
"
arg constructor"
);
}
}
class
Child
extends
Parent {
Child()
{
super
();
System.out.println(
"Flow
comes back from "
+
"Parent
class no arg const"
);
}
public
static
void
main(String[]
args)
{
new
Child();
System.out.println(
"Inside
Main"
);
}
}
Get Answers For Free
Most questions answered within 1 hours.