Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active December 28, 2015 04:09
Show Gist options
  • Save rshepherd/7440771 to your computer and use it in GitHub Desktop.
Save rshepherd/7440771 to your computer and use it in GitHub Desktop.
Demonstration of adhoc polymorphism via function overloading
public class AdHocPolymorphism {
// ad hoc polymorphism to refers to
// polymorphic functions which can be
// applied to arguments of different types,
public static class Adder {
// Note: int[] is not coercible to double[]
public static int add(int[] integers) {
int sum = 0;
for(int i = 0 ; i < integers.length ; ++i) {
sum += integers[i];
}
return sum;
}
public static double add(double[] doubles) {
double sum = 0.0;
for(int i = 0 ; i < doubles.length ; ++i) {
sum += doubles[i];
}
return sum;
}
}
// the add functions seems to work generically
// over various types when looking at the
// invocations, but are considered to be two
// distinct functions by the compiler.
public static class TestAdder {
public static void main(String[] args) {
int[] integers = {1, 2, 3, 4, 5};
System.out.println (
Adder.add(integers)
);
double[] doubles = {1d, 2d, 3d, 4d, 5d};
System.out.println (
Adder.add(doubles)
);
// won't compile
float[] floats = {1f, 2f, 3f, 4f, 5f};
System.out.println (
Adder.add(floats)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment