Overrides

23 July 2021

Overriding in Java. In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

A method in the child class, such as fly in the example below, does not need to be overridden because it does not exist in the parent class. However, the sleep method exists in the parent class but it does something different (in this case returns a different string). Since the sleep method exists in the parent class the sleep method is overridden using the annotation @Override.

Override is not the same as overload.

Override example

Parent Class:

            
                public class Animal {
                    private String animalName;
                    //public methods are visible to the calling class (ie.. Main)
                    public String sleep() {
                        return "An animal sleeps...";
                    }
                    public String eat() {
                        return "An animal eats...";
                    }
                }
            
        

Child Class:

            
                // we can extend a class into a more specific type
                // by using the keyword: extends
                public class Bird extends Animal {

                    //we can add methods specific to our Bird class
                    public String fly(){
                        return "The bird is flying";
                    }

                    //we can override methods from the parent class
                    @Override
                    public String sleep(){
                        return "The bird is sleeping";
                    }
                }
            
        

Source: Montgomery College Java Bootcamp (canvas)