The task of a programmer is to write a program which implements an algorithm. An algorithm specifies operations on data. Data can be of different types and structures. Thus, a program is an amalgamation of algorithm and data structures. Implementing the same algorithm for each different data structure, that is, just code duplication, is cumbersome. The concept of generic programming addresses this issue. With generic programming, a program can be written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. In this way, programs are related to abstract data types and such programming helps the programmer to avoid code duplication. Java features generic programming facilities and this chapter will help you to master the subject.
Introduction
Concept of generic The dictionary meaning of the word “generic” is “not specific.” This word is used as an adjective to imply a characteristic of relating to a class or group of things. For example, a generic drug, which refers to the chemical makeup of a drug and not specific to a brand name under which the drug is sold.
Definition of generic programming In the world of programming, generic is used to mean an abstraction. The term “generic programming” was coined by David R. Musser and Alexander A. Stepanov in 1989 and defined as follows:
“Generic programming centers around the idea of abstracting from concrete, efficient algorithms to obtain generic algorithms that can be combined with different data representations to produce a wide variety of useful software.”
Polymorphism versus generic programming At an early stage of generic programming (like in LISP, Ada, Smalltalk, etc.) the concept was to write common functions that differ only in the set of types on which they operate when used, thus reducing duplication. Such software entities are known as generics. Generic programming can thus be termed broadly as parametric polymorphism. The polymorphism concept is an important object-oriented programming paradigm which you are already familiar with in the context of encapsulation and inheritance. Method overloading is parametric polymorphism.
Why generic programming? With method overloading you can define two or more methods having the same name but with different signatures and different operations. So codes need to be developed for each method.
Review the options below to login to check your access.
Log in with your Cambridge Higher Education account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.