Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Java Generics: C++ class templates vs. Java class generics

2 min read

Generics are a great thing. C++ already had already a similar mechanism called templates. This for instance allowed you to write completely abstract classes which could - theoretically - be of any type. Take for instance the following:
#include <iostream>
#include <string.h>
#include <conio.h>

using namespace std;

template <class A> class Container{

A value;
Container(A val){

A getValue(){
return value;

void setValue(A val){
value = val;


int main(){
template class Container<string> *c = new Container<string>("hallo");
cout << "Printout: " << c->getValue() << "\n";
Container<int> d(3);
cout << "Printout: " << d.getValue();

In Java "templates" are called generics. They are enclosed with two <> signs. Translating the above code into Java would look as follows:

public class Container<T> {
private T t;

public Container(T t) {
this.t = t;

public T getT() {
return t;

public void setT(T t) {
this.t = t;

public void showType() {
System.out.println("\nI'm of type " + t.getClass().getSimpleName());
System.out.println("My value: " + t);

public static void main(String[] args) {
Container<String> gt = new Container<String>("Hello");
Container<Integer> gt2 = new Container<Integer>(10);


The process of setting the type of the class template (in C++) or generic is called template specialization or generics specialization. Although the two different pieces of code may look quite similar, they are a different thing in both languages. Java generics simply offer compile-time safety and eliminate the need for casts. They are implemented directly by the Java compiler as a front-end conversion, also known as type erasure. The compiler basically just erases all generic specifications (between the angle brackets) and inserts casts where necessary. Moreover it keeps track of the generics internally such that all instantiations will use the same underlying generic class at compile/run time. It is therefore somehow a process of code translation or rewriting.
A C++ template gets reproduced and re-compiled entirely whenever a template is instantiated with a new class.
The main difference is that Java generics are encapsulated. The errors are flagged when they occur and not later when the corresponding classes are used/instantiated.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus