![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The super keyword is used to invoke the super class constructor from subclass constructor function.
In Java Subclass can access all the members of superclass (base class) except private data members. When the superclass is created which wants to keep it's private data members itself only. In such type of problem Subclass cannot access these members directly.
The solution is whenever a subclass need to refer to it's immediate superclass then use of super keyword is the best solution.
We can call superclass constructor as
class classname extends SuperClassName { classname() { super(); //or super(parameter_list); } }
super() calls the no argument constructor and super(parameter_list) calls to the parameterized constructor
Program to invoke (execute) the Subclass constructor from baseclass Constructor using super keyword
class SuperCons { SuperCons(String msg) { System.out.println(msg); } } class MainMethod extends SuperCons { MainMethod() { super("I'm Parameterized Constructor from class SuperCons"); System.out.println("I'm Default Constructor from class MainMethod"); } public static void main(String args[]) { MainMethod m1 = new MainMethod(); } }
Output
In above example we have used super keyword to call Parameterized constructor from baseclass. The default constructor of superclass will not be executed if we call it's parameterized constructor using super
Using super keyword we can call the members of superclass from any function of the baseclass. See below example to understand it
We can call superclass members as
class classname extends SuperClassName { classname() { super.field_name; //or super.method_name(); } }
class BaseClass { int myValue = 100; int BaseValue = 500; void show() { System.out.println("Show from base class, My value = "+myValue); } } class DerivedClass extends BaseClass { int BaseValue; void show() { BaseValue = super.BaseValue; super.show(); System.out.println("Show from Derived class, Base Value = "+BaseValue); } public static void main(String args[]) { DerivedClass dc = new DerivedClass(); dc.show(); } }
Output
In Above Example, We have created object of class Derived Class and called it's method show(). In show() method we have initialized BaseValue variable from BaseClass using super. And also we have invoked the BaseClass method called as show in same function