My younger cousin asked me what “generics” are in Java. I thought about it for a while, and I realized that in order to give a proper explanation, the following topics need to be understood first:
- Runtime VS Compile Time errors
- Inheritance
- Polymorphism
1. Runtime VS Compile Time Errors
Compile Time Errors
In a modern IDE, such as Eclipse or IntelliJ, you have a compile-time error if your code is marked by a red line:
In this example, the IDE flags this line, because I’m setting an array list of Integers to reference a List of Strings:
We call these errors “compilation errors” or compile-time errors because the errors are caught while the IDE is trying to compile the code. Before Java code can be run/executed/started, it needs to first be compiled aka translated into Java Bytecode. During this process, the IDE can check if any of the code can’t be translated, due to invalid syntax.
You cannot run Java code that contains compilation errors.
Runtime Errors
Runtime errors are not caught by the JVM or IDE. Instead, they show up after the code has started. For example: