CS 3723/3721 Programming Languages
Generic Constructs in C++ and Java


Introduction: Generic constructs are part of the larger goal of reuseability in programming languages: one would like to write code for one project and then reuse the code on the next project. For example, it would be nice to implement a stack of one kind of object, and have the same code work for any object.

As we will see later in the course during the study of interpreted languages, one often gets reusability immediately in this setting, but at the cost of less runtime efficiency. Thus a stack in Lisp can hold any object with no further work.

For compiled languages, generic constructs are provided in a more limited fashion, so as to reach a compromise between efficiency and reusability.


C, by several methods: There are several methods to fake generic constructs in C, along with a complex legitimate method.


C++, using templates: This is the way to get genericity that is simultaneously almost as fast as the non-generic constructs, and yet is fully generic. Essentially the compiler lets one make a "textual" substitution of a typename into a parameter (like a substitution done by a text editor). After the substitution, the comiler is invoked, and sees the code as if a specific type in "hard-wired" into the construct. C++ supports this confusing construct, and Java may later.


Java, using Objects: Java allows one to work with collections of arbitrary objects, and one can determine which object is involved using the instanceof operator. This does not lead to reasonable object-oriented programming, as is explained in the links below:


Java, using interfaces: As was explained above, in handling a collection of objects of different types, there needs to be a common operation that one wants to perform on each of the objects. Thus for each type involved, you need a common function, given the same name. Providing code for this common function is what Java refers to as "implementing an interface" that contains the common function. The one can call the function given a pointer to any of the types implementing the interface, so that no code change is needed to add another object to the collection.


New generic features in Java: The next release of the Java is adding generic features, which behave somewhat like those in C++. Here is a writeup describing the new features: Catching more errors at compile time with Generic Java: A proposal to add parametric types to the Java language. This particular reference is old, and I haven't yet studied these new features.

For more on Generic Java, see Eric Allen's four-part series, Diagnosing Java code: Java generics without the pain:


Revision date: 2004-10-22. (Please use ISO 8601, the International Standard Date and Time Notation.)