Java Generic Classes
CS3381 - Object Oriented
Programming Lab
Prepared by: Your Name
What is a Generic Class?
• • A Generic class allows you to write code that
works with any data type using <T>, <K, V>,
etc.
• • Helps in creating reusable and type-safe
code.
• • No need for casting.
• • Commonly used in Java Collections.
Syntax of a Generic Class
• public class Box<T> {
• private T value;
• public void setValue(T value) {
• this.value = value;
• }
• public T getValue() {
• return value;
• }
• }
Using the Generic Class
• public class Main {
• public static void main(String[] args) {
• Box<Integer> intBox = new Box<>();
• intBox.setValue(100);
• Box<String> strBox = new Box<>();
• strBox.setValue("Hello");
• System.out.println(intBox.getValue());
• System.out.println(strBox.getValue());
• }
• }
Program Output
• Output:
• 100
• Hello
• ✔️Works with multiple types
• ✔️No casting required
Advantages of Generic Classes
• • Reusability: One class for multiple data types
• • Type Safety: Compile-time checks
• • No casting needed
• • Clean and maintainable code
Real-World Use in Collections
• • ArrayList<T>
• • HashMap<K, V>
• • HashSet<T>
• • Stack<T>
• Example:
• ArrayList<String> names = new ArrayList<>();
• names.add("Alice");