Java Method Overloading and Overriding

Explains method overloading and overriding in the Java programming language. Includes an interactive example showing which method implementation is called for various method invocations.

Prerequisites

Definitions

method overloading
two or more methods with the same name but different parameter lists in the same class or in a child class
method overriding
two methods with the same name and same parameter lists, one in the parent class and one in a child class

Demonstration

  1. Move your mouse over one of the class names, and your browser will highlight all the methods that can be called using an object of that class.
  2. Move your mouse over one of the methods m in the class diagram, and your browser will highlight all the calls to the method in the Java code.
  3. Move your mouse over one of the calls to the method m in the Java code and your browser will highlight the method that it calls in the class diagram above.
Parent
−a : int
+m(x : int, y: int) : double
+m(x : int, y: int, z: int) : double
+m(x : double, y: double) : double
 
 
{overloading}
{overloading}
{overloading}
 
|  
Child
−c : int
+m(x : int, y: int) : double
+m(x : double, s: String) : double
 
 
{overriding}
{overloading}
    Parent p = new Parent();
    p.m(7, 8);
    p.m(7, 8, -5);
    p.m(72.1, 19.6);

    p = new Child();
    Child c = new Child();
    p.m(7, 8);
    c.m(7, 8);
    p.m(7, 8, -5);
    c.m(7, 8, -5);
    p.m(72.1, 19.6);
    c.m(72.1, 19.6);
    p.m(72.1, "Wow");  // Compile error! No such method in the Parent class.
    c.m(72.1, "Wow");