Java

In Java, while arrays are covariant, collections are invariant. For example, given that a Foo is a Bar, while we have a Foo[] is a Bar[], we do not have that a Collection<Foo> is a Collection<Bar>. This implies that we cannot pass in a Collection<Foo> where a Collection<Bar> is needed. Why?

Generic methods provide a great convenience that the compiler does the type inference on them. In most cases, we can call a generic method without specifying actual types for the type parameters. However, there are some cases the type inference does not work. In these cases, we need to specify explicit type parameters.

Suppose that we need to write a program to get the date which is exactly 50 days before now. What we can do is that we get the epoch time of now, and shift backward for 50 days. It looks that the code is easy to write, but it is usually hard to avoid some insidious error and get the correct result the first time you write the code.

The curiously recurring template pattern (CRTP) is a C++ programming idiom that powers the static polymorphism, the policy-based design and many other metaprogramming techniques. Here we try to apply CRTP to Java, implementing the visitor pattern in a similar way to a C++ implementation. We compare the behavior between the implementation, and explain how the differences in behavior could be understood in terms of the differences between C++ templates and Java generics.