Inheritance: Super Keyword and Method Overriding Tutorial

If you watched my tutorial on Overriding Methods, then you learned that the overridden method in the subclass is executed by default. It is a common practice to invoke an overridden method in the superclass from within the subclass. We can invoke an overridden method in the superclass from within the subclass by using the super keyword followed by the dot operator and then the method name.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md SuperOverride
C:\Java>cd SuperOverride
C:\Java\SuperOverride>Notepad SuperOverride.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class SuperOverride {
    public static void main(String args[]) {
        new TopicSuperOverride().displayMessage();
    }
}

class Greeting {
    void displayMessage() {
        System.out.println("Hello everybody, I\'m Dan, welcome to my java tutorial series.");
    }
}

class Introduction extends Greeting {
    void displayMessage() {
        super.displayMessage();
        System.out.println("Throughout my tutorials ... by building on concepts from prior tutorials.");
    }
}

class TopicSuperOverride extends Introduction {
    void displayMessage() {
        super.displayMessage();
        System.out.println("This tutorial is about how the super keyword can affect method overriding.");
    }
}

Now switch back to the command prompt (CMD) and type in javac SuperOverride.java and press Enter.
Now type in java SuperOverride and press Enter.


C:\Java\SuperOverride>javac SuperOverride.java
C:\Java\SuperOverride>java SuperOverride
Hello everybody, I\'m Dan, welcome to my java tutorial series.
Throughout my tutorials ... by building on concepts from prior tutorials.
This tutorial is about how the super keyword can affect method overriding.


Final thoughts

Method overriding combined with the super keyword gives you the power to invoke methods from your superclass and build upon them in your subclass.


Tutorials