Wednesday, May 08, 2013

Ad hoc polymorphism With Java Example

In programming languages, ad hoc polymorphism[1] is a kind of polymorphism in which polymorphic functions can be applied to arguments of different types, because a polymorphic function can denote a number of distinct and potentially heterogeneous implementations depending on the type of argument(s) to which it is applied. It is also known as function overloading or operator overloading. The term "ad hoc" in this context is not intended to be pejorative; it refers simply to the fact that this type of polymorphism is not a fundamental feature of the type system. This is in contrast to parametric polymorphism, in which polymorphic functions are written without mention of any specific type, and can thus apply a single abstract implementation to any number of types in a transparent way. This classification was introduced by Christopher Strachey in 1967.
(ref : http://en.wikipedia.org/wiki/Ad-hoc_polymorphism)

// credit to choychoy
List list = new ArrayList(Arrays.asList(1,2,3));
int v = 1;
list.remove(v);
System.out.println(list); // prints [1, 3]

List list = new ArrayList(Arrays.asList(1,2,3));
Integer v = 1;
list.remove(v);
System.out.println(list); // prints [2, 3]

http://blog.functr.com/2012/08/java-oddities-part-ii.html
http://www.reddit.com/r/programming/comments/z2n9f/javawat_part_i/

1 comment: