Java Generics Example Tutorial - Generic Method, Class, Interface
Java Generics Example Tutorial - Generic Method, Class, Interface
Java Genrics is one of the most important feature introduced in Java 5. If you have been working
on Java Collections and with version 5 or higher, I am sure that you have used it. Generics in Java with
collection classes is very easy but it provides a lot more features than just creating the type of collection
and we will try to learn features of generics in this article. Understanding generics can become confusing
sometimes if we go with jargon words, so I would try to keep it simple and easy to understand.
1. Generics in Java
2. Java Generic Class
3. Java Generic Interface
4. Java Generic Type
5. Java Generic Method
6. Java Generics Bounded Type Parameters
7. Java Generics and Inheritance
8. Java Generic Classes and Subtyping
9. Java Generics Wildcards
1. Java Generics Upper Bounded Wildcard
2. Java Generics Unbounded Wildcard
3. Java Generics Lower bounded Wildcard
10. Subtyping using Generics Wildcard
11. Java Generics Type Erasure
Generics in Java
Generics was added in Java 5 to provide compile-time type checking and removing risk
of ClassCastException that was common while working with collection classes. The whole collection
framework was re-written to use generics for type-safety. Let’s see how generics help us using collection
classes safely.
package com.journaldev.generics;
private Object t;
package com.journaldev.generics;
public T get(){
return this.t;
}
package java.lang;
import java.util.*;
package com.journaldev.generics;
Bounded type parameters can be used with methods as well as classes and interfaces.
Java Generics supports multiple bounds also, i.e <T extends A & B & C>. In this case A can be an
interface or class. If A is class then B and C should be interfaces. We can’t have more than one class in
multiple bounds.
package com.journaldev.generics;
}
We are not allowed to assign MyClass<String> variable to MyClass<Object> variable because they are
not related, in fact MyClass<T> parent is Object.
package com.journaldev.generics;
import java.util.ArrayList;
import java.util.List;
We can pass lower bound or any super type of lower bound as an argument in this case, java compiler
allows to add lower bound object types to the list.
private T data;
private Test<T> next;
Thats all for generics in java, java generics is a really vast topic and requires a lot of time to understand
and use it effectively. This post here is an attempt to provide basic details of generics and how can we
use it to extend our program with type-safety.