Overriding versus Overloading

Overloading means name sharing. This happens when a class has (declared or inherited) several methods with the same name. In Java these methods are called variants and must have different parameter lists. When the Java compiler sees a call to a method, it selects the appropriate variant based on the number, order, and types of the inputs.

Overriding means redefining an inherited method. This happens when a class declares a method that replaces an inherited method of the same name. This would happen, for example, when the declared method has the same name and parameter list as the inherited method.

However, it can be tricky distinguishing between an overload and an override in a subclass.

1. Indicate which variant of foo will be called or write "error."

class AAA {
   void foo(int x, boolean y) { ... } //v1
   void foo(double y) { ... } // v2
}

class BBB extends AAA {
   void foo(boolean x, int y) { ... } // v3
   void foo(double z) { ... } // v4
   public static void main(String[] args) {
      AAA x = new AAA();
      AAA y = new BBB();
      BBB z = new BBB();

      x.foo(3, false);
      x.foo(10);

      y.foo(3, false);
      y.foo(true, 2);
      y.foo(10);

      z.foo(3, false);
      z.foo(true, 2);
      z.foo(10);
   }
}