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

gadget unboxing monitor September 3, 2020 Unboxing of my new LG Ultragear 27GN950-B monitor

I ordered the LG Ultragear 27GN950 from Amazon.de. I compared all the Amazon EU websites and it was the cheapest in Germany. When I ordered it showed that it would deliver in 1-2 months but luckily it came back in stock in a day or two and was dispatched right after. I got the monitor delivered to Ireland within 4-5 days.

February 28, 2020 7 Easy Ways that I use to Earn Free Crypto

Even if you’re not a crypto enthusiast you should go ahead and read this post as everyone is a “give me free money” enthusiast for sure.

February 6, 2022 My latest PC Build in 2022

I wrote a post in the past describing my crypto mining plus gaming pc and after around 2-3 years of using it, I decided to add more GPUs to it and totally dedicate it to mining crypto. Ergo, I needed a new PC for my gaming and other day-to-day tasks apart from app development. App development I do only on my mac. In this post, I would be describing all the components I used in my PC and why I chose them over others.