In this tutorial, we will write a program in java for the use of super keyword. Before that, you should have knowledge on the following topic in Java.
Java Program for Super keyword
Example of a super keyword to differentiate the members of the superclass from a subclass.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class SuperClass { int id = 20; public void display() { System.out.println("Super Class display method"); } } public class SubClass extends SuperClass { int id = 10; public void display() { System.out.println("Sub Class display method"); } public void myMethods() { // Instantiating subclass SubClass s = new SubClass(); // display method and value of sub class s.display(); System.out.println("Sub Class id:" + s.id); // display method and value of super class using super super.display(); System.out.println("Super Class id::" + super.id); } public static void main(String args[]) { SubClass sub = new SubClass(); sub.myMethods(); } } |
Output:
Base Class display method
Sub Class id:10
Super Class display method
Super Class id::20