12 Rules of Overriding in Java You Should Know

Details Written by Nam Ha Minh Last Updated on 14 August 2019 | Print Email

1. What is Overriding in Java?

Animal

Dog

Dog

move()

Animal

Dog

move()

The Dog ’s move() method is called the overriding method .

’s method is called the . The Animal ’s move() method is called the overridden method.

2. What methods can be overridden?

Rule #1: Only inherited methods can be overridden.

The Dog class overrides both the move() (public) and eat() (protected) methods from the Animal class (regardless of packages where the both classes are declared):

public class Animal { public void move() { // animal moving code... } protected void eat() { // animal eating code... } }

public class Dog extends Animal { public void move() { // dog moving code... } protected void eat() { // dog eating code... } }

In the following example, the Dog class perfectly overrides the move() method which is declared with default access modifier in the Animal class, as long as both the classes are in the same package:

package net.codejava.core; public class Animal { void move() { // Animal moving code... } }

package net.codejava.core; public class Dog extends Animal { void move() { // Dog moving code... } }

In the following example, the Dog and Animal classes are in different packages. Thus it isn’t considered an overriding because the Dog class does not inherit the Animal ’s move() method:

package net.codejava.animal; public class Animal { void move() { // Animal moving code... } }

package net.codejava.dog; import net.codejava.core.animal.Animal; public class Dog extends Animal { void move() { // Dog moving code... } }

Dog

move()

In the following example, the Animal ’s move() method is private, so the Dog ’s move() method is just a new method, not an overriding one:

public class Animal { private void move() { // Animal moving code... } }

public class Dog extends Animal { public void move() { // Dog moving code... } }

3. What methods that cannot be overridden?

Rule #2: Final and static methods cannot be overridden.

public class Animal { final void sleep() { // animal sleeping code... } }

public class Dog extends Animal { public void sleep() { // Dog sleeping code... } }

Animal

sleep()

Dog

error: sleep() in Dog cannot override sleep() in Animal public void sleep() { ^ overridden method is final 1 error

public class Animal { static void sleep() { // animal sleeping code... } }

public class Dog extends Animal { public void sleep() { // Dog sleeping code... } }

Dog

error: sleep() in Dog cannot override sleep() in Animal public void sleep() { ^ overridden method is static 1 error

4. Requirements for the overriding method

Rule #3 : The overriding method must have same argument list.

public class Animal { protected void eat(String food) { // animal eating code... } }

public class Dog extends Animal { protected void eat(String food) { // dog eating code... } }

eat()

Dog

protected void eat(String food, int amount) { // dog eating code... }

Rule #4 : The overriding method must have same return type (or subtype).

Food

DogFood

public class Animal { protected Food seekFood() { // animal seeking for food code... return new Food(); } }

public class Dog extends Animal { protected Food seekFood() { // dog seeking for food code... return new DogFood(); } }

Dog

seekFood()

DogFood

Food

protected DogFood seekFood() { // dog seeking for food code... return new DogFood(); }

Dog

seekFood()

Dog

seekFood()

protected String seekFood() { // dog seeking for food code... return new String(); }

error: seekFood() in Dog cannot override seekFood() in Animal protected String seekFood() { ^ return type String is not compatible with Food 1 error

Rule #5 : The overriding method must not have more restrictive access modifier.

If the overridden method is has default access, then the overriding one must be default, protected or public .

or . If the overridden method is protected , then the overriding one must be protected or public .

, then the overriding one must be or . If the overridden method is public , then the overriding one must be only public .

public class Animal { protected void move() { // animal moving code... } }

public class Dog extends Animal { public void move() { // Dog moving code... } }

Dog

public class Dog extends Animal { void move() { // Dog moving code... } }

move()

Rule #6 : The overriding method must not throw new or broader checked exceptions.

Animal

public class Animal { protected void move() throws IOException { // animal moving code... } }

Dog

move()

FileNotFoundException

FileIOException

public class Dog extends Animal { protected void move() throws FileNotFoundException { // Dog moving code... } }

InterruptedException

public class Dog extends Animal { protected void move() throws IOException, InterruptedException { // Dog moving code... } }

IllegalArgumentException

public class Dog extends Animal { protected void move() throws IOException, IllegalArgumentException { // Dog moving code... } }

Dog

move()

Exception

IOException

public class Dog extends Animal { protected void move() throws Exception { // Dog moving code... } }

5. Invoking the overridden method

Rule #7: Use the super keyword to invoke the overridden method from a subclass.

Overriding is a core concept inas well as in Java programming language. Understanding what it is, how it works and what the rules are is very important for every Java programmer, especially those who are preparing for the OCPJP exam (exam topic: Java Class Design > Override methods).Therefore, this tutorial compiles a comprehensive summary of concepts and rules regarding overriding in the Java language, with easy-to-understand code examples.refers to the ability of a subclass to re-implement an instance method inherited from a superclass. Let’s take a look at the following class diagram:Here,is the superclass andis the subclass, thusinherits themethod from. However,re-implements themethod for some behaviors which are specific to only dogs (like walk and run). In this respect:Basically, the overriding method must have same name and same arguments list as the overridden one. It’s the way by which a subtype extends or re-defines behaviors of its supertype.Because overriding happens when a subclass re-implements a method inherited from a superclass, so only inherited methods can be overridden, that’s straightforward. That means only methods declared with the following access modifiers: public protected and default (in the same package) can be overridden. That also means private methods cannot be overridden. Let’s see some examples:Here, the’smethod is just a new method, not an overriding one.A final method means that it cannot be re-implemented by a subclass, thus it cannot be overridden. Consider the following example:Here, the’smethod is marked as final , therefore theclass won’t compile. The compiler will complain:In case of static method , because a static method is available to all instances of the superclass and its subclasses, so it’s not permissible to re-implement the static method in a particular subclass. Consider the following example:The compiler will issue the following complaint when trying to compile theclass:With respect to the overridden method, the overriding method must obey the following rules:Let’s see the following example:Themethod of theclass is a legal overriding, as it keeps the same argument (String food) as the superclass’ version. If we add a new argument to the method like this:Then this method is not an overriding, it is an overload instead.Suppose that aclass has a subclass called, the following example shows a correct overriding:It’s possible to modify the return type of the’smethod to- a subclass of, as shown below:That’s perfectly a legal overriding, and the return type of’smethod is known as.Theclass won’t compile if we change themethod’s return type to another, as shown below:As the complier issues this error:This rule can be understood as follows:In other words, the overriding method may have less restrictive (more relaxed) access modifier. The following example shows a legal overriding:However, in the following example, theclass won’t compile:It is because themethod now has default access, which is more restrictive than the protected access of the superclass’ version.In other words, the overriding method may throw fewer or narrower checked exceptions, or any unchecked exceptions.Consider the following superclass -The following subclass -, correctly overrides themethod because theis a subclass of theThe following example shows an illegal overriding attempt because theis a new and checked exception:However, the following example is a legal overriding, because theis an unchecked exception:And in the example below, theclass won’t compile because itsmethod throwswhich is superclass (broader) of theIt’s very common that a subclass extends a superclass’ behavior rather than re-implementing the behavior from scratch. In such case, invoke the superclass’ method in the following form:

super.overriddenMethodName()

public class Animal { protected void move() { // animal moving code... } }

public class Dog extends Animal { protected void move() { super.move(); // Animal movement // Dog-specific moving code... } }

Dog

move()

Animal

Dog

move()

6. Overriding and constructor

Rule #8: Constructors cannot be overridden.

7. Overriding and abstract method

Rule #9: Abstract methods must be overridden by the first concrete (non-abstract) subclass.

public interface Animal { void move(); }

move()

AbstractDog

public abstract class AbstractDog implements Animal { protected abstract void bark(); }

BullDog

AbstractDog

Animal

public class BullDog extends AbstractDog { public void move() { // Bulldog moves... } protected void bark() { // Bulldog barks... } }

BullDog

move()

bark()

Animal

AbstractDog

8. Overriding and static method

Rule #10: A static method in a subclass may hide another static one in a superclass, and that’s called hiding.

public class Animal { static void sleep() { System.out.println("Animal sleeps"); } }

public class Dog extends Animal { static void sleep() { System.out.println("Dog sleeps"); } }

sleep()

Dog

sleep()

Animal

doSomething()

Dog

public class Dog extends Animal { static void sleep() { System.out.println("Dog sleeps"); } void doSomething() { sleep(); // this calls the hiding method // because the Animal's sleep() is hidden, it requires to use // a fully qualified class name to access it. Animal.sleep(); } }

9. Overriding and synchronized method

Rule #11: The synchronized modifier has no effect on the rules of overriding.

10. Overriding and strictfp method

Rule #12: The strictfp modifier has no effect on the rules of overriding.

Related Tutorials:



About the Author: Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on





is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Consider the following example:Here, theclass overrides themethod from theclass. Then in the’smethod, it calls the superclass’ version of the method first, then add behaviors specific to only dogs.Because constructors are not methods and a subclass’ constructor cannot have same name as a superclass’ one, so there’s nothing relates between constructors and overriding.Learn more: 9 Rules about Constructors in Java Consider the following interface:If an abstract class implements the above interface, then it doesn’t require the subclass to override themethod, as shown in the followingclass:But if a concrete (non-abstract) class, says, is a subclass of theclass or theinterface, then it must override all the inherited abstract methods, as shown below:In this respect, theclass is said totheandabstract methods of its supertypes - theinterface and theclass. Although all the rules of overriding must be obeyed in this context, the termis more exact then the term, since the overridden method is abstract.Consider the following example:Here, themethod of theclass is said tothemethod of theclass. When a static method of the superclass is hidden, it requires the subclass to use a fully qualified class name of the superclass to invoke the hidden method, as shown in themethod of theclass below:Note that the rules of overriding are still applied for the hiding method.The synchronized modifier relates to the acquiring and releasing of a monitor object in multi-threaded context, therefore it has totally no effect on the rules of overriding. That means a synchronized method can override a non-synchronized one and vice versa.That means the presence or absence of the strictfp modifier has absolutely no effect on the rules of overriding: it’s possible that a FP-strict method can override a non-FP-strict one and vice-versa.