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();
    }
}
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on May 29, 2019
Image placeholder

Keep reading

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

November 28, 2019 How I got 800 stars on GitHub in a day

Is your project solving a pain point that no other project is solving or is it solving a problem in a way better than others? If the answer is yes then read on.

referral discount wise January 5, 2021 Referral link for Transferwise (now Wise)

If you want to try out Wise (formerly Transferwise), you can use my referral link to register: https://wise.com/invite/u/ramp11 and get one international transfer (up to £500 or equivalent) totally free with no transfer fees.

March 14, 2021 Beginners guide to mine crypto with your computer

Crypto Mining nowadays has been made really easy by apps like NiceHash, CudoMiner, HoneyMiner, etc. Anyone with a computer and some decent CPU or GPU (Graphics Card) can mine and earn quick money. And, because of the rising price of Bitcoin and mining profits, everyone wants to mine nowadays. Ergo, I am putting down a short guide on how to get started with mining.