Super Keyword Interview Questions in Java
Interview Questions on Super Keyword in Java
What is super keyword ?
It is used to access members of the base class.
Can we use both "this" and "super" in a constructor ?
No, because both this and super should be the first statement.
What are usage of java super Keyword ?
- super is used to refer immediate parent class instance variable.
- super() is used to invoke immediate parent class constructor.
- super is used to invoke immediate parent class method.
When Need of super keyword ?
Whenever the derived class is inherits the base class features, there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features and derived class features must be preceded by super keyword.
Difference Between this() and super() ?
Super keyword is always pointing to base class features and this keyword is always pointing to current class features.
this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.
this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.
What is difference between super(), super(..), this() and this(..) ?
super() and super(..) are used for establishing the communication between base class and derived class constructor.
this() and this(...) are used for establishing the communication between current class constructor.
In a case where there are no instance variables what does the default constructor initialize ?
Java expects the superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.