What are Generics? Provide an example program.

3.A] What are Generics? Provide an example program.

Answer:

Generics in Java are a feature that allows you to define classes, interfaces, and methods with type parameters. This means you can create components that operate on objects of various types while providing compile-time type safety. Generics enable you to write more flexible and reusable code by allowing you to parameterize types.

Benefits of Generics:

  1. Type Safety: Prevents runtime type errors by checking types at compile-time.
  2. Code Reusability: Allows you to create classes, interfaces, and methods that can work with any type.
  3. Eliminates Casting: Removes the need for explicit type casting when retrieving elements from a collection.

Example Program: Using Generics

Let’s create a simple generic class and demonstrate its usage.

Step 1: Define a Generic Class

// Define a generic class with type parameter T
class Box<T> {
    private T content;

    public void setContent(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }
}

Explanation:

  • The Box class has a type parameter T.
  • T can be any type, and the class will operate on this type.
  • setContent() method sets the content of the box, and getContent() retrieves it.

Step 2: Use the Generic Class

public class GenericsExample {

    public static void main(String[] args) {
        // Create a Box for Integer
        Box<Integer> integerBox = new Box<>();
        integerBox.setContent(123);
        System.out.println("Integer content: " + integerBox.getContent());

        // Create a Box for String
        Box<String> stringBox = new Box<>();
        stringBox.setContent("Hello Generics!");
        System.out.println("String content: " + stringBox.getContent());
    }
}

Explanation:

  • Box<Integer>: Creates a Box instance that holds Integer values.
  • Box<String>: Creates a Box instance that holds String values.
  • The setContent() and getContent() methods work with the type specified (Integer or String).

Output:

When you run the program, you will get the following output:

Integer content: 123
String content: Hello Generics!

Key Points:

  • Generic Class: A class with a type parameter (T) that can be replaced with any type.
  • Type Safety: The compiler ensures that the type specified is consistent throughout the class.
  • Code Reusability: The same Box class can be used with different types, reducing code duplication and increasing flexibility.

Generics are widely used in Java, especially with collections such as ArrayList, HashMap, and other container classes, allowing you to specify the type of elements they store.

Leave a Reply

Your email address will not be published. Required fields are marked *