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 开发者_如何学Gois often called generic programming." (emphasis added)
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.
Yes, it's called parametric polymorphism. Your reasoning for classing it as polymorphism is spot-on.
In addition to parametric polymorphism, you'll presumably be calling the hashCode
method of objects stored in the hash table, which is an example of the polymorphism John refers to. HashTable relies on parametric polymorphism, and E relies on (plain) polymorphism.
While Rob's answer might be true in some technical sense, I don't think it's what is being asked for. I think this wikipedia article is more likely to be what you need.
精彩评论