Java Overriding

As a web developer, java overriding may not be a familiar thing for you. However, for mobile developers, this work is their everyday work, so, after discussing about super classes and subclasses, in this article we are going to explain about overriding. Overriding a method is possible when a class inherits method from its superclass, even though it is not marked as final.

Through overriding, you are able to determine a specific behavior to the subclass type. This means that based on its requirement, a subclass can implement a parent class method.

So, in object-oriented terms, overriding means to override the functionality of an existing method.

For example:
To get this output “animals can move dogs can walk and run”

The above example shows that even though b is a type of Animal, it runs the movement method in the Dog class. The reason is because in compile time, the check is made on the reference type. However, JVM can figure out the object type. Then, it would run the method in the run time, if the method belongs to that particular object.

This is why the program is able to compile properly as Animal class has the method move, so, at the runtime, it runs the method specifically for that object. Look at the following example.
Output

a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class b.bark(); }}
Since b’s type Animal doesn’t have a method by the name of bark, this program throws a compile time error.

RULES FOR METHOD OVERRIDING

You should have argument list that is exactly the same as the overridden method.

The return type should be the same or a subtype of the return type declares in the original overridden method in the superclass.

The overridden method’s access level should be more restrictive than the access level. For instance: If the superclass method is declared public then the overriding method in the sub class cannot be private nor protected.

If your instance methods are inherited by the subclass, then they can be overriding.

You cannot override a method declared final.

You also cannot override a method declared static but can re-declare.

Your method cannot be overridden, if it cannot be inherited.

A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.

The non-final methods declared public or protected can only be override by a subclass in a different package.

Regardless of whether the overridden method throws exceptions or not, an overriding method can throw any uncheck exceptions. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. Compared to overridden method, the overriding method can throw narrower or fewer exceptions.

Constructors cannot be overridden.

Using the Super KeywordSuper keyword is used when invoking a superclass version of an overridden method.
Output