Provide Best Programming Tutorials

Overriding vs. Overloading

Overloading means to define multiple methods with the same name but different signatures.

Overriding means to provide a new implementation for a method in the subclass.

Let us use an example to show the differences between overriding and overloading. In (a) below, the method p(double i) in class A overrides the same method defined in class B. In (b), however, the class A has two overloaded methods: p(double i) and p(int i) . The method p(double i) is inherited from B.

Note the following:

  • Overridden methods are in different classes related by inheritance; overloaded methods can be either in the same class or different classes related by inheritance.

  • Overridden methods have the same signature and return type; overloaded methods have the same name but a different parameter list.

To avoid mistakes, you can use a special Java syntax, called override annotation , to place

@Override before the method in the subclass. For example:

This annotation denotes that the annotated method is required to override a method in the superclass. If a method with this annotation does not override its superclass’s method, the compiler will report an error. For example, if toString is mistyped as tostring , a compile error is reported. If the override.

Questions

  1. Explain the difference between method overloading and method overriding.

  2. If a method in a subclass has the same signature as a method in its superclass with the same return type, is the method overridden or overloaded?

  3. If a method in a subclass has the same signature as a method in its superclass with a different return type, will this be a problem?

  4. If a method in a subclass has the same name as a method in its superclass with different parameter types, is the method overridden or overloaded?

  5. What is the benefit of using the @Override annotation?

Leave a Reply

Close Menu