Polymorphism (computer science): Difference between revisions

Content deleted Content added
m minor fix
Ad hoc polymorphism: Use a more familiar/commonly used language, as measured in 2023 StackOverflow dev survey's "Most Popular Technologies"
Line 20:
===Ad hoc polymorphism===
{{main|Ad hoc polymorphism}}
[[Christopher Strachey]] chose the term ''ad hoc polymorphism'' to refer to polymorphic functions that can be applied to arguments of different types, but that behave differently depending on the type of the argument to which they are applied (also known as [[function overloading]] or [[operator overloading]]).<ref name=Strachey00/> The term "[[ad hoc]]" in this context is not intended to be pejorative; it refers simply to the fact that this form of polymorphism is not a fundamental feature of the type system. In the [[PascalJava (programming language)|Pascal]] / [[Delphi (programming language)|DelphiJava]] example below, the <code>Add</code> functions seem to work generically over two types (integer and string) when looking at the invocations, but are considered to be two entirely distinct functions by the compiler for all intents and purposes:
 
<syntaxhighlight lang="PascalJava">
class AdHocPolymorphic {
program Adhoc;
public String add(int x, int y) {
return "Sum: "+(x+y);
}
 
public String add(String name) {
function Add(x, y : Integer) : Integer;
return "Added "+name;
begin
Add := x + y}
}
end;
 
public class adhoc {
function Add(s, t : String) : String;
public static void main(String[] args) {
begin
AdHocPolymorphic poly = new AdHocPolymorphic();
Add := Concat(s, t)
end;
 
System.out.println( poly.add(1,2) ); // prints "Sum: 3"
begin
System.out.println( poly.add("Jay") ); // prints "Added Jay"
Writeln(Add(1, 2)); (* Prints "3" *)
}
Writeln(Add('Hello, ', 'Mammals!')); (* Prints "Hello, Mammals!" *)
}
end.
</syntaxhighlight>