Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is generic programming an example of polymorphism?

I'm working on a homework assignment (a project), for which one criterion is that I must make use of polymorphism in a way which noticeably improves the overall quality or functionality of my code.

I made a Hash Table which looks like this:

public class HashTable<E extends Hashable>{
    ...
}

where Hashable is an interface I made that has a hash() function.

I know that using generics this way improves the quality of my code, since now HashTable can work with pretty much any type I want (instead of just ints or Strings for example). But I'm not sure if it demonstrates polymorphism.

I think it does, because E can be any type that implements Hashable. In other words HashTable is a class which can work with (practically) any type.

But I'm not quite sure - is that polymorphism? Perhaps can I get some clarification as to what exactly polymorphism is?

Thanks in advance!


Edit: After receiving the answer below (see: first answer received), I read the Wikipedia article, and came across this:

"In the object-oriented programming community, programming using parametric polymorphism is often called generic programming." (emphasis added)

like image 701
CS Student Avatar asked Mar 27 '10 20:03

CS Student


2 Answers

Polymorphism is, in a nutshell, taking many different classes which share a common base class (or interface), and treating them all as members of that common base, without knowing or caring which particular inheriting class they are or how precisely they implement the common functions. In object oriented programming, polymorphism gives you a relatively high-level view of that part of your problem domain - you're saying, "This code doesn't care about the specific details of these objects - just that they implement some common functions X,Y,Z," or "just that they're all of the basic class BaseClass."

Your example uses polymorphism, because you define a Hashable base class - and provide a function that cares only about that aspect of the objects it receives. Hashable objects may have many forms, but your code treats them all as a single basic type.

like image 157
Ziv Avatar answered Sep 18 '22 09:09

Ziv


Yes, it's called parametric polymorphism. Your reasoning for classing it as polymorphism is spot-on.

like image 28
Rob Avatar answered Sep 18 '22 09:09

Rob