Using super
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super can be used with methods and constructors as well.
Example (use super for methods)
class HelloSuper { void function1() { System.out.println("Inside Base Class"); } } class HelloSuper2 extends HelloSuper { void function1() // overriding the function method { System.out.println("Inside Derived Class"); super.function1(); // super function will be called } } public class UsingSuper { public static void main(String[] args) { HelloSuper2 H = new HelloSuper2(); // creating base class object H.function1(); // calling base class method function1 } }
Output
Inside Derived Class Inside Base Class
A second use of super. In this we demonstrate how to use super for constructors.
Example
class SuperConstructor1 { SuperConstructor1(String args) { System.out.println("Inside base class constructor, arguments : " + args); } void functionForSuperClass() { System.out.println("base class function"); } } class SuperConstructor2 extends SuperConstructor1 { SuperConstructor2() { super("calling From Super"); // calling base class constructor with super System.out.println("Inside derived class constructor"); } void functionForSuperClass2() { functionForSuperClass(); } } public class UsingSuperConstr { public static void main(String[] args) { SuperConstructor2 object = new SuperConstructor2(); } }
Output
Inside base class constructor, arguments : calling From Super Inside derived class constructor