Javac · Java Tutorials - Inheritance: Overriding Methods Tutorial

Inheritance: Overriding Methods Tutorial

Now that we have a few concepts of inheritance under our belt, I will show you how you can override a method. Overriding methods is another one of the really cool features of object-oriented programming. It was necessary to learn a few things about inheritance because method overriding can only occur in a superclass/subclass relationship. There will be situations where you extend a class and you want to modify the behavior of a method declaration in the superclass. How can we do that? We simply create a method in the subclass with the identical signature and return type. By default, when the method is invoked using an instance of an object, the method in the subclass will be the one that is executed.



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 OverridingMethods
C:\Java>cd OverridingMethods
C:\Java\OverridingMethods>Notepad OverridingMethods.java

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


class OverridingMethods {
    public static void main(String args[]) {
        Child c = new Child();
        c.displayMessage();

        Parent p = new Parent();
        p.displayMessage();

        GrandParent g = new GrandParent();
        g.displayMessage();
    }
}

class GrandParent {
    void displayMessage() {
        System.out.println("Invoking the method from the GRANDPARENT class.");
    }
}

class Parent extends GrandParent {
    void displayMessage() {
        System.out.println("Invoking the method from the PARENT class.");
    }
}

class Child extends Parent {
    void displayMessage() {
        System.out.println("Invoking the method from the CHILD class.");
    }
}


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


C:\Java\OverridingMethods>javac OverridingMethods.java
C:\Java\OverridingMethods>java OverridingMethods
Invoking the method from the CHILD class.
Invoking the method from the PARENT class.
Invoking the method from the GRANDPARENT class.


Final thoughts

On the surface, this basic example makes it seem like overriding methods is a really simple concept. In reality, the rules of overriding a method are actually quite complex as you will discover in future tutorials.


Tutorials