Generics

Generics in Java are a powerful feature introduced in Java 5 to provide type safety and reusability while working with classes, interfaces, and methods. They allow developers to write code that works with different data types without sacrificing type checking at compile time.

What Are Generics?

Generics enable you to define classes, interfaces, and methods with a placeholder for types. Instead of working with a specific data type, generics allow you to create a single class or method that automatically adapts to the type provided.

For example:

List<String> list = new ArrayList<>();

Here, String is the type parameter. This ensures that only String objects can be added to the list, providing type safety.

Why Use Generics?

Type Safety: Generics catch type errors at compile time rather than at runtime.

Code Reusability: One generic class or method can work with different types.

Eliminates Type Casting: You don’t need to manually cast objects when retrieving them.

Cleaner Code: Generics improve code readability and maintainability.

Generic Classes

You can create your own generic class like this:

class Box<T> {

    private T value;

    public void set(T value) {

        this.value = value;

    }

    public T get() {

        return value;

    }

}

Now you can use it with any data type

Box<Integer> intBox = new Box<>();

intBox.set(10);

Box<String> strBox = new Box<>();

strBox.set("Hello");

Generic Methods

Methods can also be generic:

public <T> void printArray(T[] array) {

    for (T element : array) {

        System.out.println(element);

    }

}

This method can print arrays of any type — integers, strings, or even custom objects.

Bounded Type Parameters

You can restrict the types that can be used with generics using bounds:

public <T extends Number> void printDouble(T value) {

    System.out.println(value.doubleValue());

}

This method will only accept Number types or its subclasses like Integer, Float, etc.

Conclusion

Generics make Java more robust and flexible. By allowing code to be written in a type-independent manner, they help reduce runtime errors and improve performance. Whether you're working with collections, custom classes, or utility methods, mastering generics is essential for writing clean and reusable Java code.

Learn: Java Fullstack Training In Hyderabad

Operators and Control Statements

Object-Oriented Programming (OOP) Concepts

Exception Handling

Java Collections Framework

Visit Our Quality Thought Training Institute

Comments

Popular posts from this blog

Creating Microservices with Spring Boot

SOAP Web Services (JAX-WS)

File I/O and Serialization