super Keyword
super Keyword
Understanding the super
Keyword
- The
super
keyword in Java is a reference variable which is used to refer to the immediate parent class. - It can be used to call the parent class’s constructor, methods, and variables.
- The
super
keyword helps to avoid the confusion between superclasses and subclasses that have methods or variables with the same name.
Using super
to Call Parent Class Constructors
- In the subclass constructor, you can use the
super()
method to call the constructor of the superclass. - If the use of
super()
is not explicitly declared in a subclass constructor, the Java compiler will automatically insert a no-argumentsuper()
. super()
must always be the first statement in the constructor of the subclass. If it’s not, the compiler will complain.
Using super
to Access Parent Class Methods
- If a method is overridden in the subclass, you can use
super.methodName()
to call the method from the superclass. - This becomes useful when you want to use the original behaviour of a method from the superclass in your subclass.
Using super
to Access Parent Class Variables
- Similar to methods, when a variable is declared in both the subclass and the superclass,
super.variableName
can be used to refer to the variable from the superclass. - Using
super
to refer to a variable can ensure that we are accessing or modifying the right variable when they have the same name in both superclass and subclass.
Important Points about ‘super’
- The keyword
super
is not usable in astatic
context as it is tied directly to the object instance or the subclass. super
cannot be used to call methods from a superclass that is two or more levels up in the hierarchy.- The methods and variables referred to using
super
must be accessible i.e., they can’t be private to the superclass. - The keyword
this
usually refers to current instance, butsuper
refers to the super or parent instance.