Loading...

Overriding in Java

java tech
Ram Patra Published on May 29, 2019
Image placeholder

Reimplementing the inherited method from the parent class in the child class is called Overriding in Java.

There are certain rules for overriding, the below code points out all of the rules:

class Animal {

    private void drink() {
        System.out.println("Animal Drink");
    }

    public void eat() {
        System.out.println("Animal Eat");
    }

    protected void walk() {
        System.out.println("Animal Walk");
    }

    public void run() {
        System.out.println("Animal Run");
    }

    public void sleep() throws IOException {
        System.out.println("Animal Sleep");
    }

    public Animal getAnimal() {
        return new Animal();
    }
}

class Horse extends Animal {

    private void drink() {  // Not a method override as drink()
                            // wasn't inherited by Horse class
        System.out.println("Horse Drink");
    }

    private void eat() {    // You can't use a more
                            // restrictive access modifier
                            // (gives you a compiler error)
        System.out.println("Horse Eat");
    }

    public void walk() {    // Valid method override as you can use less restrictive
                            // access modifier in the overriding method
        System.out.println("Horse Walk");

    }

    public void run(int n) {    // Not a method override (argument list differs)
                                // but rather a method overload of run() in Animal
        System.out.println("Horse Run");
    }

    public Horse getAnimal() {  // Valid method override as return type must
                                // be the same as, or a subtype of, the return type
                                // declared in the original overridden method in the superclass
        return new Horse();
    }

    public void eat() throws Exception {   // Invalid method override as the overridden method doesn't
                                           // throw any checked exceptions while overriding method does
                                           // (gives a compiler error)
        System.out.println("Horse Eat");
    }

    public void sleep() throws FileSystemException {   // Valid method override as FileSystemException
                                                       // is a subclass of IOException
        System.out.println("Horse Sleep");
    }
    
    public void sleep() {                        // Valid method override as it isn't mandatory for
                                                 // the overridden method to throw any exception
            System.out.println("Horse Sleep");
    }

    public void sleep() throws Exception {  // Invalid method override as Exception is neither
                                            // same as nor a subclass of IOException
                                            // (gives a compiler error)
        System.out.println("Horse Sleep");
    }
}

public class Overriding {

    public static void main (String [] args) {
        Animal a = new Animal();
        Animal b = new Horse();  // Animal ref, but a Horse object

        a.eat();   // Runs the Animal version of eat()
        b.eat();   // Runs the Horse version of eat()
                   // (Concept called Dynamic method invocation)

    }
}

Some more rules which may be obvious:

  • You cannot override a method marked final.
  • You cannot override a method marked static.
  • If a method can’t be inherited, you cannot override it. As said earlier, overriding implies that you’re reimplementing a method you inherited.

Dynamic Method Invocation: Overridden instance methods are dynamically invoked based on the real object’s type rather than the reference type. For example, b.eat() will actually run the Horse version of eat().

Q&A

Q1. Will the below code compile?

class Animal {
    public void eat() throws Exception {
        // throws an Exception
    }
}

class Dog extends Animal {
    public void eat() { /* no Exceptions */}

    public static void main(String[] args) {
        Animal a = new Dog();
        Dog d = new Dog();
        d.eat();
        a.eat();
    }
}
Ram Patra Published on May 29, 2019
Image placeholder

Keep reading

If you liked this article, you may like these as well

January 31, 2020 How to make a Slack Bot in Java

We will be using JBot––a tiny Java Framework––to develop a Slack Bot within minutes.

November 28, 2019 How I made my blog

I made this blog using JAMStack. J stands for Javascript, A for APIs, and M for Markups. So, in short, a website built using HTML, CSS, and Javascript only and maybe accessing some APIs over HTTP can be said to be built with JAMStack and are generally called Static Websites.

February 11, 2020 What I use for Photography?

I have been doing photography for 3 years now as a hobby and I am loving it so far, given the prolific use of social media apps nowadays like Instagram, Snapchat, etc. Having said that, I don’t do photography for social media apps. I do it for fun and I get a bonus too if it sells on Shutterstock or elsewhere.