মূল কন্টেন্টে যান
eLearner.app
মডিউল 6 · 2-এর পাঠ 2কোর্সে 12/14~15 min
মডিউল পাঠ (2/2)

জাভাতে জেনেরিক

Generics (Generic Types) were introduced in Java to allow classes, interfaces, and methods to operate on different types as parameters. This ensures compile-time type safety and avoids expensive explicit casts at runtime.

Generic Classes

A generic class is defined using angle brackets <T> where T acts as a placeholder for a type that will be specified when the class is instantiated.

Code
public class Box<T> {
    private T content;

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

    public T getContent() {
        return content;
    }
}

When creating a Box object, we specify the actual type:

Code
Box<Integer> integerBox = new Box<>();
integerBox.setContent(123);
int value = integerBox.getContent(); // No cast needed!

Generic Methods

You can define a single generic method that can accept different type parameters. The type parameter is placed before the return type of the method.

Code
public static <E> void printArray(E[] elements) {
    for (E element : elements) {
        System.out.println(element);
    }
}

Wildcards and Bounded Types

We can restrict the types accepted by a generic using the extends keyword (upper bound) to accept a specific type or its subclasses.

Code
public static <T extends Number> void processNumber(T number) {
    // Accepts Integer, Double, Float, etc.
    System.out.println(number.doubleValue());
}

Try it yourself

ব্যায়াম#java.m6.l2.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Complete the generic class Box by defining the getter getValue() that returns T and the setter setValue(T value) that sets the private variable value.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

Write the methods with the correct signature using the generic type parameter `T`.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

ব্যায়াম#java.m6.l2.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Create a static generic method printArray that takes an array of type T[] named array and prints each element using a for-each loop.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

The type parameter `<T>` must be placed immediately after `static` and before the return type `void`.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

ব্যায়াম#java.m6.l2.e3
প্রচেষ্টা: 0লোড হচ্ছে...

Create a static class StringContainer that implements the Container interface parameterized with String. Define a constructor that takes a String parameter and implement the getItem() method.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

Substitute the generic type `T` with `String` in the class signature and in the return type of `getItem()`.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ